﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Security.Cryptography;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Security;
using housingsafety.server.Snowflake;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;
using System.Text;
using Npgsql;
using Dapper;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Drawing;
using System.Text.Json;
using System.Configuration;
using NPOI.SS.Formula.Functions;
using System.Net;
using NPOI.POIFS.Properties;
using System.Web;
using System.Data.Entity.Core.Metadata.Edm;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using DocumentFormat.OpenXml.Wordprocessing;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 用户管理(Ok)
    /// </summary>
    public class AdminController : BaseController<AdminController>
    {
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmDepartment> _departmentRepository;
        private readonly ILogger m_Logger;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="userRepository">用户存储</param>
        /// <param name="mapper"></param>
        /// <param name="cacheProvider"></param>
        /// <param name="dbContext"></param>
        /// <param name="logger"></param>
        /// <param name="systemLogRepository"></param>
        /// <param name="departmentRepository"></param>
        public AdminController(IRepository<ZmUser> userRepository
            , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
            , ILogger<AdminController> logger
            , IRepository<ZmSystemLog> systemLogRepository
            , IRepository<ZmDepartment> departmentRepository) : base(logger, systemLogRepository)
        {
            _mapper = mapper;
            _dbContext = dbContext;
            _cache = cacheProvider.CreateCache();
            _userRepository = userRepository;
            _departmentRepository = departmentRepository;
        }

        /// <summary>
        /// APP日志回收
        /// </summary>
        /// <param name="sec"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("log/callback")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [AllowAnonymous]
        public RespRet Log([FromQuery] string sec, [FromBody] CreateAppLogInput request)
        {
            if ("sihuo@logmapapp".Equals(sec))
            {
                var dmSystemLog = new ZmSystemLog();
                dmSystemLog.Id = SequentialGuid.SequentialGuidGenerator.Instance.NewGuid().ToString("N");
                dmSystemLog.UserId = "app";
                dmSystemLog.UserName = "app";
                dmSystemLog.ActionName = "app";
                dmSystemLog.CreateOn = DateTime.Now;
                dmSystemLog.ModifiedOn = DateTime.Now;
                dmSystemLog.Path = Request.Path;
                dmSystemLog.LoginType = Request.Headers["User-Agent"];
                dmSystemLog.LogTime = DateTime.Now;
                dmSystemLog.Ip = this.IpAddress();
                dmSystemLog.MobileBrand = request.MobileBrand;
                dmSystemLog.MobileSystem = request.MobileSystem;
                dmSystemLog.AppVersion = request.AppVersion;
                dmSystemLog.ErrorStack = request.ErrorStack;
                _systemLogRepository.Insert(dmSystemLog);
                _systemLogRepository.SaveChanges();
            }

            return new RespRet(true, "Ok");
        }


        /// <summary>
        /// 消防消隐统计合并接口
        /// </summary>
        /// <param name="type_cs">【必填】场所类型：居住0商业1 (全部)3 </param>
        /// <param name="type_yh">【必填】隐患类型：0全部1消隐  全部3 </param>
        /// <param name="type_zx">【必填】专项类型：108,777,0(全部)</param>
        /// <param name="groupbyLever">【必填】层级：0区县,1街镇,2村级</param>
        /// <param name="groupbyLever_code">【可选_2级组合】下级行政区调用(如点击海淀区:groupbyLever=2|groupbyLever_code=110108,保留当前其他查询条件 )</param>
        /// <param name="StartTime">起始时间</param>
        /// <param name="EndTime">结束时间</param>
        [HttpGet("admin/custom-function/excutexf")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public Object QueryBySqlexcutexf([FromQuery] string type_cs, [FromQuery] string type_yh, [FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] DateTime StartTime, [FromQuery] DateTime EndTime, [FromQuery] string groupbyLever_code)
        {

            //隐患类型：0全部1消隐 2剩余 type_yh
            //场所类型：居住0商业1 type_cs
            //专项类型：108,777,0(全部) type_zx
            //分组等级：0区县,1街镇,2村级 groupbyLever

            //隐患类型规则
            //发现：全部
            //消隐：yhxc_time <>null 
            //剩余：yhxc_time=null




            string sqlstr = "";
            try
            {
                var adminUserNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(adminUserNumber))
                {
                    return new RespRet<List<object>>(false, "user not logined");
                }
                //居住或商业查询字段
                string jzorsy = "";
                int type_yhget = 1;
                //场所类型：居住0商业1

                string query = "";
                string groupquery = "";
                string cs_type = "";
                if (string.IsNullOrEmpty(type_cs))
                {
                    return new RespRet<List<object>>(false, "场所类型不能为空");
                }
                else
                {
                    if (type_cs == "0")
                    {
                        groupquery = @"  
    COALESCE(sum(sumall), 0) AS sumall,
    COALESCE(sum(use_electric_bicycle), 0) AS use_electric_bicycle,
    COALESCE(sum(use_bottled_liquefied_gas), 0) AS use_bottled_liquefied_gas,
    COALESCE(sum(use_stacked_items), 0) AS use_stacked_items,
    COALESCE(sum(use_burglar_mesh), 0) AS use_burglar_mesh,
    COALESCE(sum(use_ceiling), 0) AS use_ceiling,
    COALESCE(sum(is_completely_isolated), 0) AS is_completely_isolated,
    COALESCE(sum(use_flammable_materials), 0) AS use_flammable_materials,
    COALESCE(sum(unauthorized_electrical_connect), 0) AS unauthorized_electrical_connect,
    COALESCE(sum(not_enough_exits), 0) AS not_enough_exits,
    COALESCE(sum(use_flammable_insulation_materials), 0) AS use_flammable_insulation_materials,
    COALESCE(sum(use_flammable_dangerous_goods), 0) AS use_flammable_dangerous_goods,
    COALESCE(sum(above_three_floor_self), 0) AS above_three_floor_self,
    COALESCE(sum(charging_facilities_no_standard), 0) AS charging_facilities_no_standard";
                        query = @"  
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self  ";
                    }
                    else if (type_cs == "1")
                    {
                        groupquery = @"
    COALESCE(sum(sumall), 0) AS sumall,
    COALESCE(sum(use_electric_bicycle), 0) AS use_electric_bicycle,
    COALESCE(sum(use_bottled_liquefied_gas), 0) AS use_bottled_liquefied_gas,
    COALESCE(sum(use_stacked_items), 0) AS use_stacked_items,
    COALESCE(sum(use_burglar_mesh), 0) AS use_burglar_mesh,
    COALESCE(sum(use_ceiling), 0) AS use_ceiling,
    COALESCE(sum(is_completely_isolated), 0) AS is_completely_isolated,
    COALESCE(sum(use_flammable_materials), 0) AS use_flammable_materials,
    COALESCE(sum(unauthorized_electrical_connect), 0) AS unauthorized_electrical_connect,
    COALESCE(sum(not_enough_exits), 0) AS not_enough_exits,
    COALESCE(sum(use_flammable_insulation_materials), 0) AS use_flammable_insulation_materials,
    COALESCE(sum(use_flammable_dangerous_goods), 0) AS use_flammable_dangerous_goods,
    COALESCE(sum(above_three_floor_self), 0) AS above_three_floor_self,
    COALESCE(sum(fire_service_damaged), 0) AS fire_service_damaged,
    COALESCE(sum(use_store_dangerous_goods), 0) AS use_store_dangerous_goods,
    COALESCE(sum(threaten_safety_fire_hazards), 0) AS threaten_safety_fire_hazards";
                        query = @"
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",		
(
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end),0 )+
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 )+
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 )+
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 )+ 
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 )+
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 )
) AS sumall,
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end ),0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 ) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 ) as use_stacked_items,
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 ) as use_burglar_mesh,
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 ) as use_ceiling,
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 ) as is_completely_isolated,
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 ) as use_flammable_materials,
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 ) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 ) as not_enough_exits,
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 ) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 ) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 ) as above_three_floor_self,
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 ) as fire_service_damaged,
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 ) as use_store_dangerous_goods,
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 ) as threaten_safety_fire_hazards ";
                    }
                    else if (type_cs == "3")
                    {
                        groupquery = @" 
    COALESCE(sum(sumall), 0) AS sumall,
    COALESCE(sum(use_electric_bicycle), 0) AS use_electric_bicycle,
    COALESCE(sum(use_bottled_liquefied_gas), 0) AS use_bottled_liquefied_gas,
    COALESCE(sum(use_stacked_items), 0) AS use_stacked_items,
    COALESCE(sum(use_burglar_mesh), 0) AS use_burglar_mesh,
    COALESCE(sum(use_ceiling), 0) AS use_ceiling,
    COALESCE(sum(is_completely_isolated), 0) AS is_completely_isolated,
    COALESCE(sum(use_flammable_materials), 0) AS use_flammable_materials,
    COALESCE(sum(unauthorized_electrical_connect), 0) AS unauthorized_electrical_connect,
    COALESCE(sum(not_enough_exits), 0) AS not_enough_exits,
    COALESCE(sum(use_flammable_insulation_materials), 0) AS use_flammable_insulation_materials,
    COALESCE(sum(use_flammable_dangerous_goods), 0) AS use_flammable_dangerous_goods,
    COALESCE(sum(above_three_floor_self), 0) AS above_three_floor_self,
    COALESCE(sum(fire_service_damaged), 0) AS fire_service_damaged,
    COALESCE(sum(use_store_dangerous_goods), 0) AS use_store_dangerous_goods,
    COALESCE(sum(charging_facilities_no_standard), 0) AS charging_facilities_no_standard,
    COALESCE(sum(threaten_safety_fire_hazards), 0) AS threaten_safety_fire_hazards";
                        query = @" 
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) +
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self,
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) as fire_service_damaged,
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) as use_store_dangerous_goods,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0) as threaten_safety_fire_hazards";
                    }
                    else
                    {
                        return new RespRet<List<object>>(false, "专项类型错误");
                    }
                }

                //type_yh = "1";
                if (string.IsNullOrEmpty(type_yh))
                {
                    return new RespRet<List<object>>(false, "隐患类型不能为空");
                }

                string str = "";
                if (type_yh == "0")
                {
                    str = "yhfx_time";
                }
                else
                {
                    str = "yhxc_time";
                }
                string isxcyh = "";
                if (type_yh == "0")
                {
                    type_yh = " and yhfx_time is not null ";
                }
                else if (type_yh == "1")
                {
                    isxcyh = "1";
                    type_yh = @$" and   ( t.yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<'2023/3/16 0:00:00' )";
                }
                else if (type_yh == "2")
                {
                    //type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time between '{StartTime}' and '{EndTime}') ";
                    type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time <= '{EndTime}') and yhfx_time<'2023/3/16 0:00:00' ";
                    str = "2";
                }
                //时间区间查询
                string querydate = "";
                if (StartTime != null && EndTime != null)
                {
                    querydate = $" and(t.{str} between '{StartTime}' and '{EndTime}' )";
                }
                //如果是剩余 
                if (str == "2")
                {
                    querydate = "";
                }

                string zx = "";
                string dccode = "";
                if (string.IsNullOrEmpty(type_zx))
                {
                    return new RespRet<List<object>>(false, "专项类型不能为空");
                }
                else
                {
                    if (type_zx == "777")
                    {

                        zx = @" and check777 = '1'";
                    }
                    else if (type_zx == "108")
                    {
                        zx = @" and check108 = '1'";
                    }
                    else if (type_zx == "0")
                    {
                        zx = "";
                    }
                }
                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<List<object>>(false, "用户名不存在");
                }
                // var curuserDto = _mapper.Map<UserDto>(curuser);

                string codewhere = "";
                //根据用户角色过滤
                if (curuser.RoleType > 1)
                {
                    if (curuser.RoleType == 3)
                    {
                        JObject obj = JObject.Parse(curuser.District);
                        string RegionCode = (string)obj["RegionCode"];
                        codewhere = $"and xzqdm='{RegionCode}'";
                    }
                    else if (curuser.RoleType == 4)
                    {
                        JObject obj = JObject.Parse(curuser.District);
                        string RegionCode = (string)obj["RegionCode"];
                        codewhere = $"and town='{RegionCode}'";

                    }
                    else if (curuser.RoleType == 5)
                    {
                        JObject obj = JObject.Parse(curuser.District);
                        string RegionCode = (string)obj["RegionCode"];
                        codewhere = $"and village='{RegionCode}'";

                    }
                }

                string xzqdm = "xzqdm";
                string groupname = "";
                string getdatabycode = "";
                if (groupbyLever == "0")
                {
                    groupname = ") a group by xzqdm";
                    if (groupbyLever_code != null)

                        getdatabycode = $"and xzqdm='{groupbyLever_code}'"; if (groupbyLever_code == "110000")
                    {
                        getdatabycode = " ";
                    }
                }
                else if (groupbyLever == "1")
                {
                    groupname = ") a group by town";
                    if (groupbyLever_code != null)
                    {
                        getdatabycode = $"and xzqdm='{groupbyLever_code}'";
                    }
                    xzqdm = "town";
                }
                else if (groupbyLever == "2")
                {
                    xzqdm = "village";
                    groupname = ") a group by village";
                    if (groupbyLever_code != null)
                    {
                        getdatabycode = $"and town='{groupbyLever_code}'";
                    }
                }
                else
                {
                    return new RespRet<List<object>>(false, "分组格式不正确");
                }

                string querystr = @$" select max(village) village,max({xzqdm}) xzqdm,COALESCE(sum(ypc_sl), 0)as ypc_sl,
     max(villagename) AS villagename, max(xzqdmname) xzqdmname, max(town) town, max(townname)townname,
   {groupquery}
 from(";
                sqlstr = @$"{querystr} select  dc.village,COALESCE(tmp.ypc_sl, 0)as ypc_sl,
      dc.villagename AS villagename,
          dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,
         {query}  from
(select village, villagename,xzqdm,xzqdmname,town,townname from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171') {codewhere} {getdatabycode} {zx} GROUP BY village, villagename,xzqdm,xzqdmname,town,townname order by village) dc
      left join
      (
      select
 count(Distinct (t.fwbh)) as ypc_sl,
     h.village,h.town,h.xzqdm {type_cs}
      from zm_xf_pc_detailed t,
      zm_buildings_layer h
      WHERE t.fwbh::text = h.fwbh::text  AND(h.is_delete IS NULL OR h.is_delete <> 1)
      {type_yh} {cs_type} {querydate}  GROUP BY  h.village,h.xzqdm,h.town   ) tmp  on dc.village = tmp.village" + groupname + "  ORDER BY village";
                //防止注入
                if (sqlstr.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("update ", StringComparison.OrdinalIgnoreCase))
                {
                    return new RespRet<List<object>>(false, "不符合规范，禁止执行");
                }
                if (isxcyh == "1")
                {
                    if (groupbyLever == "0")
                    {
                        sqlstr = @$"select b.*,case when  a.cl_scfw315 is not null then a.cl_scfw315 else 0 end as ypc_sl from(select xzqdm,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and house_id not in ( select DISTINCT(house_id) from ( select xzqdm,house_id,
case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<'2023/3/16 0:00:00'
GROUP BY xzqdm,house_id) and yhxc_time >'{EndTime}' and yhfx_time <'2023-03-15 23:59:59' then  ts.house_id end cl_scfw315
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx} )
)a where cl_scfw315 is not null)  and yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315 --315前消除隐患房屋 
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')   {zx} )
GROUP BY xzqdm)  a RIGHT JOIN ({sqlstr}) b on a.xzqdm=b.xzqdm";

                    }
                    if (groupbyLever == "1")
                    {
                        sqlstr = @$"select b.*,case when  a.cl_scfw315 is not null then a.cl_scfw315 else 0 end as ypc_sl from(select xzqdm,town,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and house_id not in ( select DISTINCT(house_id) from ( select xzqdm,house_id,
case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<'2023/3/16 0:00:00'
GROUP BY xzqdm,house_id) and yhxc_time >'{EndTime}' and yhfx_time <'2023-03-15 23:59:59' then  ts.house_id end cl_scfw315
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx} )
)a where cl_scfw315 is not null)  and yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315 --315前消除隐患房屋 
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')   {zx} )
GROUP BY xzqdm,town)  a RIGHT JOIN ({sqlstr}) b on a.town=b.town";
                    }
                    if (groupbyLever == "2")
                    {
                        sqlstr = @$"select b.*,case when  a.cl_scfw315 is not null then a.cl_scfw315 else 0 end as ypc_sl from(select xzqdm,town,village,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and house_id not in ( select DISTINCT(house_id) from ( select xzqdm,house_id,
case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<'2023/3/16 0:00:00'
GROUP BY xzqdm,house_id) and yhxc_time >'{EndTime}' and yhfx_time <'2023-03-15 23:59:59' then  ts.house_id end cl_scfw315
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx} )
)a where cl_scfw315 is not null)  and yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315 --315前消除隐患房屋 
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')   {zx} )
GROUP BY xzqdm,town,village)  a RIGHT JOIN ({sqlstr}) b on a.village=b.village";
                    }
                }
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();
                return new RespRet<List<object>>(true, "Ok", datas);
            }
            catch (Exception ex)
            {

                return "异常，请检查参数后重试" + sqlstr;
            }

        }



        /// <summary>
        /// 隐患单向明细表
        /// </summary>
        /// <param name="type_cs">【必填】场所类型：居住0商业1 (全部)3 </param>
        /// <param name="type_yh">【必填】隐患类型：0全部1消隐,2剩余  全部3 </param>
        /// <param name="type_zx">【必填】专项类型：108,777,0(全部)</param>
        /// <param name="groupbyLever">【必填】层级：0区县,1街镇,2村级</param>
        /// <param name="groupbyLever_code">【必填_2级组合】下级行政区调用(如点击海淀区:groupbyLever=2|groupbyLever_code=110108,保留当前其他查询条件 )</param>
        /// <param name="groupbyLever_code_project">【必填_3级组合】单隐患项明细(如点击 海淀区的(疏散通道或安全出口数量不足或严重堵塞) 如果:groupbyLever=2|groupbyLever_code=110108|groupbyLever_code_project=not_enough_exits)</param>
        /// <param name="StartTime">起始时间</param>
        /// <param name="EndTime">结束时间</param>
        [HttpGet("admin/custom-function/excutexf_pronum")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<Page<object>> QueryBySqlexcutexf_pronum([FromQuery] string type_cs, [FromQuery] string type_yh, [FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] DateTime StartTime, [FromQuery] DateTime EndTime, [FromQuery] string groupbyLever_code, [FromQuery] string groupbyLever_code_project, [FromQuery] int pageindex, [FromQuery] int pagesize)
        {

            //隐患类型：0全部1消隐 2剩余 type_yh
            //场所类型：居住0商业1 type_cs
            //专项类型：108,777,0(全部) type_zx
            //分组等级：0区县,1街镇,2村级 groupbyLever

            //隐患类型规则
            //发现：全部 不带条件
            //消隐：yhxc_time is not null 
            //剩余：yhxc_time is null

            string sqlstr = "";
            try
            {
                var adminUserNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(adminUserNumber))
                {
                    return new RespRet<Page<object>>(false, "user not logined");
                }
                var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == user)
                {
                    return new RespRet<Page<object>>(false, "用户名不存在");
                }
                if (string.IsNullOrEmpty(groupbyLever))
                {
                    return new RespRet<Page<object>>(false, "分组等级是必须的");
                }

                //居住或商业查询字段
                string jzorsy = "";
                int type_yhget = 1;
                //场所类型：居住0商业1

                string query = "";





                string cs_type = "";
                if (string.IsNullOrEmpty(type_cs))
                {
                    return new RespRet<Page<object>>(false, "场所类型不能为空");
                }
                if (string.IsNullOrEmpty(groupbyLever_code))
                {
                    return new RespRet<Page<object>>(false, "行政区代码不能为空");
                }
                else
                {
                    if (type_cs == "0")
                    {
                        query = @"   
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self  ";
                    }
                    else if (type_cs == "1")
                    {
                        query = @"
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",		
(
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end),0 )+
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 )+
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 )+
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 )+ 
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 )+
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 )
) AS sumall,
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end ),0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 ) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 ) as use_stacked_items,
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 ) as use_burglar_mesh,
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 ) as use_ceiling,
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 ) as is_completely_isolated,
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 ) as use_flammable_materials,
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 ) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 ) as not_enough_exits,
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 ) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 ) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 ) as above_three_floor_self,
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 ) as fire_service_damaged,
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 ) as use_store_dangerous_goods,
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 ) as threaten_safety_fire_hazards ";
                    }
                    else if (type_cs == "3")
                    {
                        query = @" 
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) +
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self,
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) as fire_service_damaged,
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) as use_store_dangerous_goods,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0) as threaten_safety_fire_hazards";
                    }
                    else
                    {
                        return new RespRet<Page<object>>(false, "专项类型错误");
                    }
                }

                //type_yh = "1";
                if (string.IsNullOrEmpty(type_yh))
                {
                    return new RespRet<Page<object>>(false, "隐患类型不能为空");
                }

                string str = "";
                if (type_yh == "0")
                {
                    str = "yhfx_time";
                }
                else
                {
                    str = "yhxc_time";
                }

                if (type_yh == "0")
                {
                    type_yh = " and yhfx_time is not null ";
                }
                else if (type_yh == "1")
                {
                    type_yh = @$" and   ( tt.yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<'2023/3/16 0:00:00' )";
                }
                else if (type_yh == "2")
                {
                    //type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time between '{StartTime}' and '{EndTime}') ";
                    type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(yhfx_time <= '{EndTime}') and yhfx_time<'2023/3/16 0:00:00' ";
                    str = "2";
                }

                //时间区间查询
                string querydate = "";
                if (StartTime != null && EndTime != null)
                {
                    querydate = $" and({str} between '{StartTime}' and '{EndTime}' )";
                }
                //如果是剩余 
                if (str == "2")
                {
                    querydate = "";
                }



                string zx = "";
                string dccode = "";
                if (string.IsNullOrEmpty(type_zx))
                {
                    return new RespRet<Page<object>>(false, "专项类型不能为空");
                }
                else
                {
                    if (type_zx == "777")
                    {

                        zx = @" and check777 = '1'";
                    }
                    else if (type_zx == "108")
                    {
                        zx = @" and check108 = '1'";
                    }
                    else if (type_zx == "0")
                    {
                        zx = "";
                    }
                }

                string code = "";
                string name = "";
                string getdatabycode = "";
                if (groupbyLever == "0")
                {
                    code = "xzqdm";
                    name = "xzqdmname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.xzqdm='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "1")
                {
                    code = "town";
                    name = "townname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.town='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "2")
                {
                    code = "village";
                    name = "villagename";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.village='{groupbyLever_code}'";
                    }
                }
                else
                {
                    return new RespRet<Page<object>>(false, "分组格式不正确");
                }

                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<Page<object>>(false, "用户名不存在");
                }
                var curuserDto = _mapper.Map<UserDto>(curuser);

                if (string.IsNullOrEmpty(groupbyLever_code_project))
                {
                    return new RespRet<Page<object>>(false, "隐患名称不能为空");
                }

                //                sqlstr = @$"select  dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,t.fwbh,prosum from
                //(select xzqdm,town,village,fwbh,count(project_name) as prosum from zm_xf_pc_detailed 
                //where project_name='{groupbyLever_code_project}'   {type_yh} 
                // GROUP BY  xzqdm,town,village,fwbh ) t  
                //left join
                //(select  xzqdm,xzqdmname,town,townname,village,villagename from zm_department_xf_2023 where regional_level='7' GROUP BY xzqdm,xzqdmname,town,townname,village,villagename ) dc
                //on t.village = dc.village";
                //这里是分组语句
                //                if (groupbyLever == "2")
                //                {
                //                    sqlstr = @$"   select a.*,zm.place_name from  (select a.*,zm.address from  (select   place_id,house_id,dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,t.fwbh,prosum from
                //                (select place_id,house_id, xzqdm,town,village,fwbh,count(project_name) as prosum from zm_xf_pc_detailed 
                //                where project_name='{groupbyLever_code_project}' {type_yh} {cs_type}{zx}{getdatabycode}{querydate}
                //                 GROUP BY  xzqdm,town,village,fwbh,place_id,house_id ) t  
                //                left join
                //                (select  xzqdm,xzqdmname,town,townname,village,villagename from zm_department_xf_2023 where regional_level='7' GROUP BY xzqdm,xzqdmname,town,townname,village,villagename ) dc
                //                on t.village = dc.village) a left join zm_buildings zm on a.house_id=zm.id)a left join zm_place_resident zm on a.place_id=zm.id

                //";
                //                }
                //                else if (groupbyLever == "1")
                //                {
                //                    sqlstr = @$"  			select a.*,v.region_name as villagename from (select a.*,zm.place_name from  (select a.*,zm.address,zm.village from  (select   place_id,house_id,dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,t.fwbh,prosum from
                //                (select place_id,house_id,xzqdm,town,fwbh,count(project_name) as prosum from zm_xf_pc_detailed 
                //                 where project_name='{groupbyLever_code_project}' {type_yh} {cs_type}{zx}{getdatabycode}{querydate}
                //                 GROUP BY  xzqdm,town,fwbh,place_id,house_id ) t  
                //                left join
                //                (select  xzqdm,xzqdmname,town,townname from zm_department_xf_2023 where regional_level='7' GROUP BY xzqdm,xzqdmname,town,townname ) dc
                //                on t.town = dc.town) a left join zm_buildings zm on a.house_id=zm.id)a left join zm_place_resident zm on a.place_id=zm.id	)a left join zm_department_xf_2023 v on a.village=v.region_code												
                //";
                //                }
                //                else if (groupbyLever == "0")
                //                {
                //                    sqlstr = @$" select a.*,t.region_name as townname from (select a.*,v.region_name as villagename from ( select a.*,zm.place_name from  (select a.*,zm.address,zm.village,zm.town from  (select   place_id,house_id,dc.xzqdm,dc.xzqdmname,t.fwbh,prosum from
                //                (select place_id,house_id, xzqdm,fwbh,count(project_name) as prosum from zm_xf_pc_detailed 
                //                where project_name='{groupbyLever_code_project}' {type_yh} {cs_type}{zx}{getdatabycode}{querydate}
                //                 GROUP BY  xzqdm,fwbh,place_id,house_id ) t  
                //                left join
                //                (select  xzqdm,xzqdmname from zm_department_xf_2023 where regional_level='7' GROUP BY xzqdm,xzqdmname) dc
                //                on t.xzqdm = dc.xzqdm) a left join zm_buildings zm on a.house_id=zm.id)a left join zm_place_resident zm on a.place_id=zm.id)a left join zm_department_xf_2023 v on a.village=v.region_code) a left join zm_department_xf_2023 t on a.town=t.region_code

                //";
                //                }
                //if (groupbyLever == "2")
                //{
                sqlstr = @$" select  csmc,(select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,  yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time,dc.xzqdm, dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh, case  type  when 0 then '居住'else '商业' END as cstype,zb.address,csmc as place_name  from zm_xf_pc_detailed 
                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate} ORDER BY village	 limit {pagesize} offset {(pageindex - 1) * pagesize}							
";
                var total = @$" select   csmc  from zm_xf_pc_detailed 
                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate} ORDER BY tt.village						
";
                //防止注入
                if (sqlstr.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("update ", StringComparison.OrdinalIgnoreCase))
                {
                    return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
                }
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();
                var totals = _dbContext.Database.GetDbConnection().Query<object>(total).ToList();
                return new RespRet<Page<object>>(true, "Ok", new Page<object> { NextPageIndex = pageindex + 1, Items = datas, PageSize = pagesize, PageTotal = totals.Count(), Total = totals.Count() });
            }
            catch (Exception ex)
            {

                return new RespRet<Page<object>>(false, "请检查参数后重试");
            }
        }



        /// <summary>
        /// 隐患单向明细表导出
        /// </summary>
        /// <param name="type_cs">【必填】场所类型：居住0商业1 (全部)3 </param>
        /// <param name="type_yh">【必填】隐患类型：0全部1消隐,2剩余  全部3 </param>
        /// <param name="type_zx">【必填】专项类型：108,777,0(全部)</param>
        /// <param name="groupbyLever">【必填】层级：0区县,1街镇,2村级</param>
        /// <param name="groupbyLever_code">【必填_2级组合】下级行政区调用(如点击海淀区:groupbyLever=2|groupbyLever_code=110108,保留当前其他查询条件 )</param>
        /// <param name="groupbyLever_code_project">【必填_3级组合】单隐患项明细(如点击 海淀区的(疏散通道或安全出口数量不足或严重堵塞) 如果:groupbyLever=2|groupbyLever_code=110108|groupbyLever_code_project=not_enough_exits)</param>
        /// <param name="StartTime">起始时间</param>
        /// <param name="EndTime">结束时间</param>
        [HttpGet("admin/custom-function/excutexf_pronum_Import")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public object excutexf_pronum_Import([FromQuery] string type_cs, [FromQuery] string type_yh, [FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] DateTime StartTime, [FromQuery] DateTime EndTime, [FromQuery] string groupbyLever_code, [FromQuery] string groupbyLever_code_project, [FromQuery] int pageindex, [FromQuery] int pagesize)
        {

            //隐患类型：0全部1消隐 2剩余 type_yh
            //场所类型：居住0商业1 type_cs
            //专项类型：108,777,0(全部) type_zx
            //分组等级：0区县,1街镇,2村级 groupbyLever

            //隐患类型规则
            //发现：全部 不带条件
            //消隐：yhxc_time is not null 
            //剩余：yhxc_time is null

            string sqlstr = "";
            try
            {
                var adminUserNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(adminUserNumber))
                {
                    return new RespRet<Page<object>>(false, "user not logined");
                }
                var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == user)
                {
                    return new RespRet<Page<object>>(false, "用户名不存在");
                }
                if (string.IsNullOrEmpty(groupbyLever))
                {
                    return new RespRet<Page<object>>(false, "分组等级是必须的");
                }

                //居住或商业查询字段
                string jzorsy = "";
                int type_yhget = 1;
                //场所类型：居住0商业1

                string query = "";





                string cs_type = "";
                if (string.IsNullOrEmpty(type_cs))
                {
                    return new RespRet<Page<object>>(false, "场所类型不能为空");
                }
                if (string.IsNullOrEmpty(groupbyLever_code))
                {
                    return new RespRet<Page<object>>(false, "行政区代码不能为空");
                }
                else
                {
                    if (type_cs == "0")
                    {
                        query = @"   
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self  ";
                    }
                    else if (type_cs == "1")
                    {
                        query = @"
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",		
(
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end),0 )+
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 )+
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 )+
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 )+ 
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 )+
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 )
) AS sumall,
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end ),0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 ) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 ) as use_stacked_items,
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 ) as use_burglar_mesh,
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 ) as use_ceiling,
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 ) as is_completely_isolated,
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 ) as use_flammable_materials,
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 ) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 ) as not_enough_exits,
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 ) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 ) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 ) as above_three_floor_self,
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 ) as fire_service_damaged,
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 ) as use_store_dangerous_goods,
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 ) as threaten_safety_fire_hazards ";
                    }
                    else if (type_cs == "3")
                    {
                        query = @" 
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) +
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self,
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) as fire_service_damaged,
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) as use_store_dangerous_goods,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0) as threaten_safety_fire_hazards";
                    }
                    else
                    {
                        return new RespRet<Page<object>>(false, "专项类型错误");
                    }
                }

                //type_yh = "1";
                if (string.IsNullOrEmpty(type_yh))
                {
                    return new RespRet<Page<object>>(false, "隐患类型不能为空");
                }

                string str = "";
                if (type_yh == "0")
                {
                    str = "yhfx_time";
                }
                else
                {
                    str = "yhxc_time";
                }

                if (type_yh == "0")
                {
                    type_yh = " and yhfx_time is not null ";
                }
                else if (type_yh == "1")
                {
                    type_yh = @$" and   ( tt.yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<'2023/3/16 0:00:00' )";
                }
                else if (type_yh == "2")
                {
                    //type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time between '{StartTime}' and '{EndTime}') ";
                    type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(yhfx_time <= '{EndTime}') and yhfx_time<'2023/3/16 0:00:00' ";
                    str = "2";
                }

                //时间区间查询
                string querydate = "";
                if (StartTime != null && EndTime != null)
                {
                    querydate = $" and({str} between '{StartTime}' and '{EndTime}' )";
                }
                //如果是剩余 
                if (str == "2")
                {
                    querydate = "";
                }



                string zx = "";
                string dccode = "";
                if (string.IsNullOrEmpty(type_zx))
                {
                    return new RespRet<Page<object>>(false, "专项类型不能为空");
                }
                else
                {
                    if (type_zx == "777")
                    {

                        zx = @" and check777 = '1'";
                    }
                    else if (type_zx == "108")
                    {
                        zx = @" and check108 = '1'";
                    }
                    else if (type_zx == "0")
                    {
                        zx = "";
                    }
                }

                string code = "";
                string name = "";
                string getdatabycode = "";
                if (groupbyLever == "0")
                {
                    code = "xzqdm";
                    name = "xzqdmname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.xzqdm='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "1")
                {
                    code = "town";
                    name = "townname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.town='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "2")
                {
                    code = "village";
                    name = "villagename";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.village='{groupbyLever_code}'";
                    }
                }
                else
                {
                    return new RespRet<Page<object>>(false, "分组格式不正确");
                }

                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<Page<object>>(false, "用户名不存在");
                }
                var curuserDto = _mapper.Map<UserDto>(curuser);

                if (string.IsNullOrEmpty(groupbyLever_code_project))
                {
                    return new RespRet<Page<object>>(false, "隐患名称不能为空");
                }


                sqlstr = @$" select   csmc,(select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,  yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time,dc.xzqdm, dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh, case  type  when 0 then '居住'else '商业' END as cstype,zb.address,csmc as place_name  from zm_xf_pc_detailed 
                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate} ORDER BY tt.village							
";

                //防止注入
                if (sqlstr.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("update ", StringComparison.OrdinalIgnoreCase))
                {
                    return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
                }
                var datas = _dbContext.Database.GetDbConnection().Query<ZxYh>(sqlstr).ToList();
                {
                    IWorkbook wb = new XSSFWorkbook();
                    ISheet sheet = wb.CreateSheet("Sheet1");
                    IRow row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue("序列");
                    row.CreateCell(1).SetCellValue("区县名称");
                    row.CreateCell(2).SetCellValue("街道名称");
                    row.CreateCell(3).SetCellValue("村庄名称");
                    row.CreateCell(5).SetCellValue("房屋地址");
                    row.CreateCell(6).SetCellValue("房屋编号");
                    row.CreateCell(7).SetCellValue("场所名称");
                    row.CreateCell(8).SetCellValue("场所类型");
                    row.CreateCell(9).SetCellValue("发现人员");
                    row.CreateCell(10).SetCellValue("发现时间");
                    row.CreateCell(11).SetCellValue("消隐人员");
                    row.CreateCell(12).SetCellValue("消隐时间");
                    // 第二行 写数据
                    int i = 1;
                    foreach (var item in datas)
                    {
                        row = sheet.CreateRow(i);
                        row.CreateCell(0).SetCellValue(i);
                        row.CreateCell(1).SetCellValue(item.xzqdmname);
                        row.CreateCell(2).SetCellValue(item.townname);
                        row.CreateCell(3).SetCellValue(item.villagename);
                        row.CreateCell(5).SetCellValue(item.address);
                        row.CreateCell(6).SetCellValue(item.fwbh);
                        row.CreateCell(7).SetCellValue(item.csmc);
                        row.CreateCell(8).SetCellValue(item.cstype);
                        row.CreateCell(9).SetCellValue(item.yhfx_name);
                        row.CreateCell(11).SetCellValue(item.yhxc_name);

                        ICell cell = row.CreateCell(10);
                        if (item.yhfx_time != null)
                        {
                            ICellStyle style = wb.CreateCellStyle();
                            IDataFormat format = wb.CreateDataFormat();
                            style.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");
                            cell.CellStyle = style;
                            string formattedDate = item.yhfx_time.ToString("yyyy-MM-dd HH:mm:ss");
                            cell.SetCellValue(formattedDate);
                        }

                        ICell cell2 = row.CreateCell(12);
                        if (item.yhxc_time != item.yhxctime)
                        {
                            ICellStyle style2 = wb.CreateCellStyle();
                            IDataFormat format2 = wb.CreateDataFormat();
                            style2.DataFormat = format2.GetFormat("yyyy-MM-dd HH:mm:ss");
                            cell2.CellStyle = style2;
                            string formattedDate2 = item.yhxc_time.ToString("yyyy-MM-dd HH:mm:ss");
                            cell2.SetCellValue(formattedDate2);
                        }
                        i++;
                    }
                    // 写 WorkBook信息到 内存流中
                    byte[] buffer = null;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        wb.Write(ms);
                        buffer = ms.ToArray();
                    }
                    return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "隐患统计(分项明细).xlsx");
                }
            }
            catch (Exception ex)
            {

                return new RespRet<Page<object>>(false, "请检查参数后重试");
            }
        }

        /// <summary>
        /// 隐患单向明细表按照房屋
        /// </summary>
        /// <param name="type_cs">【必填】场所类型：居住0商业1 (全部)3 </param>
        /// <param name="type_yh">【必填】隐患类型：0全部1消隐,2剩余  全部3 </param>
        /// <param name="type_zx">【必填】专项类型：108,777,0(全部)</param>
        /// <param name="groupbyLever">【必填】层级：0区县,1街镇,2村级</param>
        /// <param name="groupbyLever_code">【必填_2级组合】下级行政区调用(如点击海淀区:groupbyLever=2|groupbyLever_code=110108,保留当前其他查询条件 )</param>
        /// <param name="groupbyLever_code_project">【必填_3级组合】单隐患项明细(如点击 海淀区的(疏散通道或安全出口数量不足或严重堵塞) 如果:groupbyLever=2|groupbyLever_code=110108|groupbyLever_code_project=not_enough_exits)</param>
        /// <param name="StartTime">起始时间</param>
        /// <param name="EndTime">结束时间</param>
        [HttpGet("admin/custom-function/excutexf_pronum_fw")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public Object QueryBySqlexcutexf_pronum_fw([FromQuery] string type_cs, [FromQuery] string type_yh, [FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] DateTime StartTime, [FromQuery] DateTime EndTime, [FromQuery] string groupbyLever_code, [FromQuery] string groupbyLever_code_project, [FromQuery] int pageindex, [FromQuery] int pagesize)
        {

            //隐患类型：0全部1消隐 2剩余 type_yh
            //场所类型：居住0商业1 type_cs
            //专项类型：108,777,0(全部) type_zx
            //分组等级：0区县,1街镇,2村级 groupbyLever

            //隐患类型规则
            //发现：全部 不带条件
            //消隐：yhxc_time is not null 
            //剩余：yhxc_time is null

            string sqlstr = "";
            try
            {
                var adminUserNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(adminUserNumber))
                {
                    return new RespRet<List<object>>(false, "user not logined");
                }
                var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == user)
                {
                    return new RespRet<Page<ZmYtBuildDto>>(false, "用户名不存在");
                }
                if (string.IsNullOrEmpty(groupbyLever))
                {
                    return new RespRet<List<object>>(false, "分组等级是必须的");
                }

                //居住或商业查询字段
                string jzorsy = "";
                int type_yhget = 1;
                //场所类型：居住0商业1

                string query = "";
                string cs_type = "";
                if (string.IsNullOrEmpty(type_cs))
                {
                    return new RespRet<List<object>>(false, "场所类型不能为空");
                }
                if (string.IsNullOrEmpty(groupbyLever_code))
                {
                    return new RespRet<List<object>>(false, "行政区代码不能为空");
                }
                else
                {
                    if (type_cs == "0")
                    {
                        query = @"   
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self  ";
                    }
                    else if (type_cs == "1")
                    {
                        query = @"
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",		
(
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end),0 )+
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 )+
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 )+
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 )+ 
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 )+
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 )
) AS sumall,
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end ),0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 ) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 ) as use_stacked_items,
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 ) as use_burglar_mesh,
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 ) as use_ceiling,
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 ) as is_completely_isolated,
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 ) as use_flammable_materials,
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 ) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 ) as not_enough_exits,
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 ) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 ) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 ) as above_three_floor_self,
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 ) as fire_service_damaged,
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 ) as use_store_dangerous_goods,
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 ) as threaten_safety_fire_hazards ";
                    }
                    else if (type_cs == "3")
                    {
                        query = @" 
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) +
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self,
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) as fire_service_damaged,
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) as use_store_dangerous_goods,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0) as threaten_safety_fire_hazards";
                    }
                    else
                    {
                        return new RespRet<List<object>>(false, "专项类型错误");
                    }
                }

                //type_yh = "1";
                if (string.IsNullOrEmpty(type_yh))
                {
                    return new RespRet<List<object>>(false, "隐患类型不能为空");
                }

                string str = "";
                if (type_yh == "0")
                {
                    str = "yhfx_time";
                }
                else
                {
                    str = "yhxc_time";
                }

                if (type_yh == "0")
                {
                    type_yh = " and yhfx_time is not null ";
                }
                else if (type_yh == "1")
                {
                    type_yh = @$" and   ( tt.yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<'2023/3/16 0:00:00'  )";
                }
                else if (type_yh == "2")
                {
                    //type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time between '{StartTime}' and '{EndTime}') ";
                    type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(yhfx_time <= '{EndTime}') and yhfx_time<'2023/3/16 0:00:00' ";
                    str = "2";
                }

                //时间区间查询
                string querydate = "";
                if (StartTime != null && EndTime != null)
                {
                    querydate = $" and({str} between '{StartTime}' and '{EndTime}' )";
                }
                //如果是剩余 
                if (str == "2")
                {
                    querydate = "";
                }



                string zx = "";
                string dccode = "";
                if (string.IsNullOrEmpty(type_zx))
                {
                    return new RespRet<List<object>>(false, "专项类型不能为空");
                }
                else
                {
                    if (type_zx == "777")
                    {

                        zx = @" and check777 = '1'";
                    }
                    else if (type_zx == "108")
                    {
                        zx = @" and check108 = '1'";
                    }
                    else if (type_zx == "0")
                    {
                        zx = "";
                    }
                }

                string code = "";
                string name = "";
                string getdatabycode = "";
                if (groupbyLever == "0")
                {
                    code = "xzqdm";
                    name = "xzqdmname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.xzqdm='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "1")
                {
                    code = "town";
                    name = "townname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.town='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "2")
                {
                    code = "village";
                    name = "villagename";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.village='{groupbyLever_code}'";
                    }
                }
                else
                {
                    return new RespRet<List<object>>(false, "分组格式不正确");
                }

                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<List<object>>(false, "用户名不存在");
                }
                var curuserDto = _mapper.Map<UserDto>(curuser);

                if (string.IsNullOrEmpty(groupbyLever_code_project))
                {
                    return new RespRet<List<object>>(false, "隐患名称不能为空");
                }



                sqlstr = @$"  select   dc.xzqdm, dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh,house_id,max(address) as address,count(1) from zm_xf_pc_detailed 
                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate}  	GROUP BY house_id,dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh ORDER BY village	limit {pagesize} offset {(pageindex - 1) * pagesize}								
";
                var totalsql = @$"  select   dc.xzqdm, dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh,house_id,max(address) as address,count(1) from zm_xf_pc_detailed 
                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate}  	GROUP BY house_id,dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh ORDER BY village									
";

                //                sqlstr = @$" select    (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,  yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time,dc.xzqdm, dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh, case  type  when 0 then '居住'else '商业' END as cstype,zb.address,csmc as place_name  from zm_xf_pc_detailed 
                //                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                //                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                //                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate} 								
                //";
                //防止注入
                if (sqlstr.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("update ", StringComparison.OrdinalIgnoreCase))
                {
                    return new RespRet<List<object>>(false, "不符合规范，禁止执行");
                }
                var totals = _dbContext.Database.GetDbConnection().Query<object>(totalsql).ToList();
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();
                return new RespRet<Page<object>>(true, "Ok", new Page<object> { Total = totals.Count(), PageTotal = totals.Count(), PageSize = pagesize, Items = datas, NextPageIndex = pageindex + 1 });
            }
            catch (Exception ex)
            {
                return "异常，请检查参数后重试";
            }
        }




        /// <summary>
        /// 隐患单向明细表按照房屋导出
        /// </summary>
        /// <param name="type_cs">【必填】场所类型：居住0商业1 (全部)3 </param>
        /// <param name="type_yh">【必填】隐患类型：0全部1消隐,2剩余  全部3 </param>
        /// <param name="type_zx">【必填】专项类型：108,777,0(全部)</param>
        /// <param name="groupbyLever">【必填】层级：0区县,1街镇,2村级</param>
        /// <param name="groupbyLever_code">【必填_2级组合】下级行政区调用(如点击海淀区:groupbyLever=2|groupbyLever_code=110108,保留当前其他查询条件 )</param>
        /// <param name="groupbyLever_code_project">【必填_3级组合】单隐患项明细(如点击 海淀区的(疏散通道或安全出口数量不足或严重堵塞) 如果:groupbyLever=2|groupbyLever_code=110108|groupbyLever_code_project=not_enough_exits)</param>
        /// <param name="StartTime">起始时间</param>
        /// <param name="EndTime">结束时间</param>
        [HttpGet("admin/custom-function/excutexf_pronum_fw_Import")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public Object excutexf_pronum_fw_Import([FromQuery] string type_cs, [FromQuery] string type_yh, [FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] DateTime StartTime, [FromQuery] DateTime EndTime, [FromQuery] string groupbyLever_code, [FromQuery] string groupbyLever_code_project, [FromQuery] int pageindex, [FromQuery] int pagesize)
        {

            //隐患类型：0全部1消隐 2剩余 type_yh
            //场所类型：居住0商业1 type_cs
            //专项类型：108,777,0(全部) type_zx
            //分组等级：0区县,1街镇,2村级 groupbyLever

            //隐患类型规则
            //发现：全部 不带条件
            //消隐：yhxc_time is not null 
            //剩余：yhxc_time is null

            string sqlstr = "";
            try
            {
                var adminUserNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(adminUserNumber))
                {
                    return new RespRet<List<object>>(false, "user not logined");
                }
                var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == user)
                {
                    return new RespRet<Page<ZmYtBuildDto>>(false, "用户名不存在");
                }
                if (string.IsNullOrEmpty(groupbyLever))
                {
                    return new RespRet<List<object>>(false, "分组等级是必须的");
                }

                //居住或商业查询字段
                string jzorsy = "";
                int type_yhget = 1;
                //场所类型：居住0商业1

                string query = "";
                string cs_type = "";
                if (string.IsNullOrEmpty(type_cs))
                {
                    return new RespRet<List<object>>(false, "场所类型不能为空");
                }
                if (string.IsNullOrEmpty(groupbyLever_code))
                {
                    return new RespRet<List<object>>(false, "行政区代码不能为空");
                }
                else
                {
                    if (type_cs == "0")
                    {
                        query = @"   
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self  ";
                    }
                    else if (type_cs == "1")
                    {
                        query = @"
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",		
(
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end),0 )+
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 )+
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 )+
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 )+ 
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 )+
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 )+
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 )+
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 )
) AS sumall,
COALESCE(sum(case when project_name='use_electric_bicycle' then 1 end ),0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name='use_bottled_liquefied_gas' then 1 end ),0 ) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name='use_stacked_items' then 1 end ),0 ) as use_stacked_items,
COALESCE(sum(case when project_name='use_burglar_mesh' then 1 end ),0 ) as use_burglar_mesh,
COALESCE(sum(case when project_name='use_ceiling' then 1 end ),0 ) as use_ceiling,
COALESCE(sum(case when project_name='is_completely_isolated' then 1 end ),0 ) as is_completely_isolated,
COALESCE(sum(case when project_name='use_flammable_materials' then 1 end ),0 ) as use_flammable_materials,
COALESCE(sum(case when project_name='unauthorized_electrical_connect' then 1 end ),0 ) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name='not_enough_exits' then 1 end ),0 ) as not_enough_exits,
COALESCE(sum(case when project_name='use_flammable_insulation_materials' then 1 end ),0 ) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name='use_flammable_dangerous_goods' then 1 end ),0 ) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name='above_three_floor_self' then 1 end ),0 ) as above_three_floor_self,
COALESCE(sum(case when project_name='fire_service_damaged' then 1 end ),0 ) as fire_service_damaged,
COALESCE(sum(case when project_name='use_store_dangerous_goods' then 1 end ),0 ) as use_store_dangerous_goods,
COALESCE(sum(case when project_name='threaten_safety_fire_hazards' then 1 end ),0 ) as threaten_safety_fire_hazards ";
                    }
                    else if (type_cs == "3")
                    {
                        query = @" 
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        type_cs = @",(
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) +
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) +
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) +
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) +
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) +
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) +
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0)
) AS sumall,
COALESCE(sum(case when project_name = 'use_electric_bicycle' then 1 end), 0 ) as use_electric_bicycle,
COALESCE(sum(case when project_name = 'use_bottled_liquefied_gas' then 1 end), 0) as use_bottled_liquefied_gas,
COALESCE(sum(case when project_name = 'use_stacked_items' then 1 end), 0) as use_stacked_items,
COALESCE(sum(case when project_name = 'use_burglar_mesh' then 1 end), 0) as use_burglar_mesh,
COALESCE(sum(case when project_name = 'use_ceiling' then 1 end), 0) as use_ceiling,
COALESCE(sum(case when project_name = 'is_completely_isolated' then 1 end), 0) as is_completely_isolated,
COALESCE(sum(case when project_name = 'use_flammable_materials' then 1 end), 0) as use_flammable_materials,
COALESCE(sum(case when project_name = 'unauthorized_electrical_connect' then 1 end), 0) as unauthorized_electrical_connect,
COALESCE(sum(case when project_name = 'not_enough_exits' then 1 end), 0) as not_enough_exits,
COALESCE(sum(case when project_name = 'use_flammable_insulation_materials' then 1 end), 0) as use_flammable_insulation_materials,
COALESCE(sum(case when project_name = 'use_flammable_dangerous_goods' then 1 end), 0) as use_flammable_dangerous_goods,
COALESCE(sum(case when project_name = 'above_three_floor_self' then 1 end), 0) as above_three_floor_self,
COALESCE(sum(case when project_name = 'fire_service_damaged' then 1 end), 0) as fire_service_damaged,
COALESCE(sum(case when project_name = 'use_store_dangerous_goods' then 1 end), 0) as use_store_dangerous_goods,
COALESCE(sum(case when project_name = 'charging_facilities_no_standard' then 1 end), 0) as charging_facilities_no_standard,
COALESCE(sum(case when project_name = 'threaten_safety_fire_hazards' then 1 end), 0) as threaten_safety_fire_hazards";
                    }
                    else
                    {
                        return new RespRet<List<object>>(false, "专项类型错误");
                    }
                }

                //type_yh = "1";
                if (string.IsNullOrEmpty(type_yh))
                {
                    return new RespRet<List<object>>(false, "隐患类型不能为空");
                }

                string str = "";
                if (type_yh == "0")
                {
                    str = "yhfx_time";
                }
                else
                {
                    str = "yhxc_time";
                }

                if (type_yh == "0")
                {
                    type_yh = " and yhfx_time is not null ";
                }
                else if (type_yh == "1")
                {
                    type_yh = @$" and   ( tt.yhxc_time between '{StartTime}' and '{EndTime}'  and yhfx_time<'2023/3/16 0:00:00')";
                }
                else if (type_yh == "2")
                {
                    //type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time between '{StartTime}' and '{EndTime}') ";
                    type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(yhfx_time <= '{EndTime}') and yhfx_time<'2023/3/16 0:00:00' ";
                    str = "2";
                }

                //时间区间查询
                string querydate = "";
                if (StartTime != null && EndTime != null)
                {
                    querydate = $" and({str} between '{StartTime}' and '{EndTime}' )";
                }
                //如果是剩余 
                if (str == "2")
                {
                    querydate = "";
                }



                string zx = "";
                string dccode = "";
                if (string.IsNullOrEmpty(type_zx))
                {
                    return new RespRet<List<object>>(false, "专项类型不能为空");
                }
                else
                {
                    if (type_zx == "777")
                    {

                        zx = @" and check777 = '1'";
                    }
                    else if (type_zx == "108")
                    {
                        zx = @" and check108 = '1'";
                    }
                    else if (type_zx == "0")
                    {
                        zx = "";
                    }
                }

                string code = "";
                string name = "";
                string getdatabycode = "";
                if (groupbyLever == "0")
                {
                    code = "xzqdm";
                    name = "xzqdmname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.xzqdm='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "1")
                {
                    code = "town";
                    name = "townname";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.town='{groupbyLever_code}'";
                    }
                }
                else if (groupbyLever == "2")
                {
                    code = "village";
                    name = "villagename";
                    if (!string.IsNullOrEmpty(groupbyLever_code))
                    {
                        getdatabycode = $"and tt.village='{groupbyLever_code}'";
                    }
                }
                else
                {
                    return new RespRet<List<object>>(false, "分组格式不正确");
                }

                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<List<object>>(false, "用户名不存在");
                }
                var curuserDto = _mapper.Map<UserDto>(curuser);

                if (string.IsNullOrEmpty(groupbyLever_code_project))
                {
                    return new RespRet<List<object>>(false, "隐患名称不能为空");
                }



                sqlstr = @$"  select   dc.xzqdm, dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh,max(address) as address,count(1) from zm_xf_pc_detailed 
                           tt,zm_department_xf_2023 dc,zm_buildings_layer zb
                   where  tt.village = dc.village  and zb.bh = tt.house_id                    
                        and  tt.project_name='{groupbyLever_code_project}' and tt.xzqdm not in ('110101','110102','110171') {type_yh} {cs_type}{zx}{getdatabycode}{querydate}  	GROUP BY house_id,dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,dc.village,dc.villagename,zb.fwbh ORDER BY village				
";

                //防止注入
                if (sqlstr.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("update ", StringComparison.OrdinalIgnoreCase))
                {
                    return new RespRet<List<object>>(false, "不符合规范，禁止执行");
                }
                var datas = _dbContext.Database.GetDbConnection().Query<ZxFw>(sqlstr).ToList();
                IWorkbook wb = new XSSFWorkbook();
                ISheet sheet = wb.CreateSheet("Sheet1");
                IRow row = sheet.CreateRow(0);
                row.CreateCell(0).SetCellValue("序列");
                row.CreateCell(1).SetCellValue("区县名称");
                row.CreateCell(2).SetCellValue("街道名称");
                row.CreateCell(3).SetCellValue("村庄名称");
                row.CreateCell(4).SetCellValue("房屋地址");
                row.CreateCell(5).SetCellValue("房屋编号");


                // 第二行 写数据
                int i = 1;
                foreach (var item in datas)
                {
                    row = sheet.CreateRow(i);
                    row.CreateCell(0).SetCellValue(i);
                    row.CreateCell(1).SetCellValue(item.xzqdmname);
                    row.CreateCell(2).SetCellValue(item.townname);
                    row.CreateCell(3).SetCellValue(item.villagename);
                    row.CreateCell(5).SetCellValue(item.
                        fwbh);
                    row.CreateCell(4).SetCellValue(item.address);
                    ICellStyle style = wb.CreateCellStyle();
                    IDataFormat format = wb.CreateDataFormat();
                    i++;
                }
                // 写 WorkBook信息到 内存流中
                byte[] buffer = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "隐患统计(分项明细).xlsx");
            }
            catch (Exception ex)
            {

                return "异常，请检查参数后重试";
            }
        }



        /// <summary>
        /// 销账汇总导出
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="exportOption"></param>
        /// <returns></returns>
        [HttpGet("admin/custom-function/GeneralDetail_Import")]
        [Produces("application/octet-stream")]
        [ProducesResponseType(200)]
        [ProducesResponseType(401)]
        public Object GeneralDetail_Import([FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] string groupbyLever_code, string groupbyLever_code_project, int pageindex, int pagesize)
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<object>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<List<object>>(false, "用户名不存在");
            }
            if (type_zx == "777")
            {
                type_zx = "and v.check777 = '1'";
            }
            else if (type_zx == "108")
            {
                type_zx = "and v.check108 = '1'";
            }
            else if (type_zx == "107")
            {
                type_zx = "and v.check107 = '1'";
            }
            else
            {
                type_zx = " ";
            }
            string sql = "";

            string codewhere = "";
            //根据用户角色过滤
            if (curuser.RoleType > 1)
            {
                if (curuser.RoleType == 3)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and xzqdm='{RegionCode}'";
                }
                else if (curuser.RoleType == 4)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and town='{RegionCode}'";
                    if (groupbyLever == "0" || groupbyLever == "1")
                    {
                        groupbyLever = "2";
                    }
                }
                else if (curuser.RoleType == 5)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and village='{RegionCode}'";
                    groupbyLever = "2";
                }
            }

            if (string.IsNullOrEmpty(groupbyLever))
            {
                return new RespRet<List<object>>(false, "分组等级必须传递");
            }
            if (groupbyLever == "0")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    if (groupbyLever_code == "110000")
                    {
                        groupbyLever_code = " ";
                    }
                    else
                    {
                        groupbyLever_code = $"and qx.region_code='{groupbyLever_code}' ";
                    }

                }
            }
            if (groupbyLever == "1")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and jd.region_code='{groupbyLever_code}' ";
                }
            }
            if (groupbyLever == "2")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and v.region_code='{groupbyLever_code}' ";
                }
            }
            //存量房屋有隐
            if (groupbyLever_code_project == "fxhouse315")
            {
                groupbyLever_code_project = "fw";
                sql = @$"select  zm.fwbh,qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,address ,v.region_name villagename,v.region_code village
 
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7'  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY village  ";
            }
            //存量房屋消除
            if (groupbyLever_code_project == "cl_scfw315")
            {
                sql = @$"select qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is not null and zm.fwbh not in (select zm.fwbh
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is  null  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name  ORDER BY  v.region_code)  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY  v.region_code  ";

            }
            //存量房屋剩余
            if (groupbyLever_code_project == "cl_syfw315")
            {
                groupbyLever_code_project = "fw";
                sql = @$"select  zm.fwbh,qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,address ,v.region_name villagename,v.region_code village
 
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is  null  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name  ORDER BY village ";
            }
            //存量隐患数量
            if (groupbyLever_code_project == "cl_fx315")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time<='2023-03-15 23:59:59' ORDER BY village  ";
            }
            //存量隐患消除
            if (groupbyLever_code_project == "cl_xc315")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhxc_time is not null  and yhfx_time<='2023-03-15 23:59:59' ORDER BY village  ";
            }
            //存量隐患剩余
            if (groupbyLever_code_project == "cl_sy315")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time<='2023-03-15 23:59:59'  and (yhxc_time is null ) ORDER BY village  ";
            }
            //新增隐患数
            if (groupbyLever_code_project == "xz")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' ORDER BY village  ";
            }

            //新增消除隐患数
            if (groupbyLever_code_project == "xc_all")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' and yhxc_time is not null ORDER BY village   ";
            }

            //新增剩余隐患数
            if (groupbyLever_code_project == "sy_all")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' and yhxc_time is  null ORDER BY village  ";
            }

            //新增剩余隐患数
            if (groupbyLever_code_project == "sy_315")
            {
                groupbyLever_code_project = "yh";
                sql = @$"select case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName,fw.fwbh, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and   yhxc_time is  null ORDER BY village  ";
            }

            //存量房屋消除
            if (groupbyLever_code_project == "xyyhfw")
            {
                groupbyLever_code_project = "fw";
                sql = @$"select   qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code  {type_zx}  {groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is null  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY village ";
            }
            //防止注入
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
            || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
            || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<List<object>>(false, "不符合规范，禁止执行");
            }
            var datas = _dbContext.Database.GetDbConnection().Query<ZxYh>(sql).ToList();

            if (groupbyLever_code_project == "yh")
            {
                IWorkbook wb = new XSSFWorkbook();
                ISheet sheet = wb.CreateSheet("Sheet1");
                IRow row = sheet.CreateRow(0);
                row.CreateCell(0).SetCellValue("序列");
                row.CreateCell(1).SetCellValue("区县名称");
                row.CreateCell(2).SetCellValue("街道名称");
                row.CreateCell(3).SetCellValue("村庄名称");
                row.CreateCell(5).SetCellValue("房屋地址");
                row.CreateCell(6).SetCellValue("房屋编号");
                row.CreateCell(7).SetCellValue("场所名称");
                row.CreateCell(8).SetCellValue("场所类型");
                row.CreateCell(9).SetCellValue("发现人员");
                row.CreateCell(10).SetCellValue("发现时间");
                row.CreateCell(11).SetCellValue("消隐人员");
                row.CreateCell(12).SetCellValue("消隐时间");
                // 第二行 写数据
                int i = 1;
                foreach (var item in datas)
                {
                    row = sheet.CreateRow(i);
                    row.CreateCell(0).SetCellValue(i);
                    row.CreateCell(1).SetCellValue(item.xzqdmname);
                    row.CreateCell(2).SetCellValue(item.townname);
                    row.CreateCell(3).SetCellValue(item.villagename);
                    row.CreateCell(5).SetCellValue(item.address);
                    row.CreateCell(6).SetCellValue(item.fwbh);
                    row.CreateCell(7).SetCellValue(item.csmc);
                    row.CreateCell(8).SetCellValue(item.cstype);
                    row.CreateCell(9).SetCellValue(item.yhfx_name);
                    row.CreateCell(11).SetCellValue(item.yhxc_name);

                    ICell cell = row.CreateCell(10);
                    if (item.yhfx_time != null)
                    {
                        ICellStyle style = wb.CreateCellStyle();
                        IDataFormat format = wb.CreateDataFormat();
                        style.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");
                        cell.CellStyle = style;
                        string formattedDate = item.yhfx_time.ToString("yyyy-MM-dd HH:mm:ss");
                        cell.SetCellValue(formattedDate);
                    }

                    ICell cell2 = row.CreateCell(12);
                    if (item.yhxc_time != item.yhxctime)
                    {
                        ICellStyle style2 = wb.CreateCellStyle();
                        IDataFormat format2 = wb.CreateDataFormat();
                        style2.DataFormat = format2.GetFormat("yyyy-MM-dd HH:mm:ss");
                        cell2.CellStyle = style2;
                        string formattedDate2 = item.yhxc_time.ToString("yyyy-MM-dd HH:mm:ss");
                        cell2.SetCellValue(formattedDate2);
                    }
                    i++;
                }
                // 写 WorkBook信息到 内存流中
                byte[] buffer = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "隐患统计(销账汇总).xlsx");
            }
            else
            {
                IWorkbook wb = new XSSFWorkbook();
                ISheet sheet = wb.CreateSheet("Sheet1");
                IRow row = sheet.CreateRow(0);
                row.CreateCell(0).SetCellValue("序列");
                row.CreateCell(1).SetCellValue("区县名称");
                row.CreateCell(2).SetCellValue("街道名称");
                row.CreateCell(3).SetCellValue("村庄名称");
                row.CreateCell(4).SetCellValue("房屋地址");
                row.CreateCell(5).SetCellValue("房屋编号");


                // 第二行 写数据
                int i = 1;
                foreach (var item in datas)
                {
                    row = sheet.CreateRow(i);
                    row.CreateCell(0).SetCellValue(i);
                    row.CreateCell(1).SetCellValue(item.xzqdmname);
                    row.CreateCell(2).SetCellValue(item.townname);
                    row.CreateCell(3).SetCellValue(item.villagename);
                    row.CreateCell(4).SetCellValue(item.address);
                    row.CreateCell(5).SetCellValue(item.
                        fwbh);

                    ICellStyle style = wb.CreateCellStyle();
                    IDataFormat format = wb.CreateDataFormat();
                    i++;
                }
                // 写 WorkBook信息到 内存流中
                byte[] buffer = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "隐患统计(销账汇总).xlsx");
            }
        }


        /// <summary>
        /// 消防消隐统计合并接口-房屋
        /// </summary>
        /// <param name="type_cs">【必填】场所类型：居住0商业1 (全部)3 </param>
        /// <param name="type_yh">【必填】隐患类型：0全部1消隐  全部3 </param>
        /// <param name="type_zx">【必填】专项类型：108,777,0(全部)</param>
        /// <param name="groupbyLever">【必填】层级：0区县,1街镇,2村级</param>
        /// <param name="groupbyLever_code">【可选_2级组合】下级行政区调用(如点击海淀区:groupbyLever=2|groupbyLever_code=110108,保留当前其他查询条件 )</param>
        /// <param name="StartTime">起始时间</param>
        /// <param name="EndTime">结束时间</param>
        [HttpGet("admin/custom-function/excutexf_fw")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public Object QueryBySqlexcutexf_fw([FromQuery] string type_cs, [FromQuery] string type_yh, [FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] DateTime StartTime, [FromQuery] DateTime EndTime, [FromQuery] string groupbyLever_code, [FromQuery] int pageindex, int pagesize)
        {
            //隐患类型：0全部1消隐 2剩余 type_yh
            //场所类型：居住0商业1 type_cs
            //专项类型：108,777,0(全部) type_zx
            //分组等级：0区县,1街镇,2村级 groupbyLever

            //隐患类型规则
            //发现：全部
            //消隐：yhxc_time <>null 
            //剩余：yhxc_time=null


            string sqlstr = "";
            try
            {
                var adminUserNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(adminUserNumber))
                {
                    return new RespRet<List<object>>(false, "user not logined");
                }
                //居住或商业查询字段
                string jzorsy = "";
                int type_yhget = 1;
                //场所类型：居住0商业1

                string query = "";
                string groupquery = "";
                string cs_type = "";
                if (string.IsNullOrEmpty(type_cs))
                {
                    return new RespRet<List<object>>(false, "场所类型不能为空");
                }
                else
                {
                    if (type_cs == "0")
                    {
                        groupquery = @"  
    COALESCE(sum(sumall), 0) AS sumall,
    COALESCE(sum(use_electric_bicycle), 0) AS use_electric_bicycle,
    COALESCE(sum(use_bottled_liquefied_gas), 0) AS use_bottled_liquefied_gas,
    COALESCE(sum(use_stacked_items), 0) AS use_stacked_items,
    COALESCE(sum(use_burglar_mesh), 0) AS use_burglar_mesh,
    COALESCE(sum(use_ceiling), 0) AS use_ceiling,
    COALESCE(sum(is_completely_isolated), 0) AS is_completely_isolated,
    COALESCE(sum(use_flammable_materials), 0) AS use_flammable_materials,
    COALESCE(sum(unauthorized_electrical_connect), 0) AS unauthorized_electrical_connect,
    COALESCE(sum(not_enough_exits), 0) AS not_enough_exits,
    COALESCE(sum(use_flammable_insulation_materials), 0) AS use_flammable_insulation_materials,
    COALESCE(sum(use_flammable_dangerous_goods), 0) AS use_flammable_dangerous_goods,
    COALESCE(sum(above_three_floor_self), 0) AS above_three_floor_self,
    COALESCE(sum(charging_facilities_no_standard), 0) AS charging_facilities_no_standard";
                        query = @"  
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",(
COALESCE(count(DISTINCT(case when project_name = 'use_electric_bicycle' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_bottled_liquefied_gas' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_stacked_items' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_burglar_mesh' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_ceiling' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'is_completely_isolated' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_materials' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'unauthorized_electrical_connect' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'charging_facilities_no_standard' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'not_enough_exits' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_insulation_materials' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_dangerous_goods' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'above_three_floor_self' then t.house_id end)), 0)
) AS sumall,
COALESCE(count(DISTINCT(case when project_name = 'use_electric_bicycle' then t.house_id end)), 0 ) as use_electric_bicycle,
COALESCE(count(DISTINCT(case when project_name = 'use_bottled_liquefied_gas' then t.house_id end)), 0) as use_bottled_liquefied_gas,
COALESCE(count(DISTINCT(case when project_name = 'use_stacked_items' then t.house_id end)), 0) as use_stacked_items,
COALESCE(count(DISTINCT(case when project_name = 'use_burglar_mesh' then t.house_id end)), 0) as use_burglar_mesh,
COALESCE(count(DISTINCT(case when project_name = 'use_ceiling' then t.house_id end)), 0) as use_ceiling,
COALESCE(count(DISTINCT(case when project_name = 'is_completely_isolated' then t.house_id end)), 0) as is_completely_isolated,
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_materials' then t.house_id end)), 0) as use_flammable_materials,
COALESCE(count(DISTINCT(case when project_name = 'unauthorized_electrical_connect' then t.house_id end)), 0) as unauthorized_electrical_connect,
COALESCE(count(DISTINCT(case when project_name = 'charging_facilities_no_standard' then t.house_id end)), 0) as charging_facilities_no_standard,
COALESCE(count(DISTINCT(case when project_name = 'not_enough_exits' then t.house_id end)), 0) as not_enough_exits,
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_insulation_materials' then t.house_id end)), 0) as use_flammable_insulation_materials,
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_dangerous_goods' then t.house_id end)), 0) as use_flammable_dangerous_goods,
COALESCE(count(DISTINCT(case when project_name = 'above_three_floor_self' then t.house_id end)), 0) as above_three_floor_self  ";
                    }
                    else if (type_cs == "1")
                    {
                        groupquery = @"
    COALESCE(sum(sumall), 0) AS sumall,
    COALESCE(sum(use_electric_bicycle), 0) AS use_electric_bicycle,
    COALESCE(sum(use_bottled_liquefied_gas), 0) AS use_bottled_liquefied_gas,
    COALESCE(sum(use_stacked_items), 0) AS use_stacked_items,
    COALESCE(sum(use_burglar_mesh), 0) AS use_burglar_mesh,
    COALESCE(sum(use_ceiling), 0) AS use_ceiling,
    COALESCE(sum(is_completely_isolated), 0) AS is_completely_isolated,
    COALESCE(sum(use_flammable_materials), 0) AS use_flammable_materials,
    COALESCE(sum(unauthorized_electrical_connect), 0) AS unauthorized_electrical_connect,
    COALESCE(sum(not_enough_exits), 0) AS not_enough_exits,
    COALESCE(sum(use_flammable_insulation_materials), 0) AS use_flammable_insulation_materials,
    COALESCE(sum(use_flammable_dangerous_goods), 0) AS use_flammable_dangerous_goods,
    COALESCE(sum(above_three_floor_self), 0) AS above_three_floor_self,
    COALESCE(sum(fire_service_damaged), 0) AS fire_service_damaged,
    COALESCE(sum(use_store_dangerous_goods), 0) AS use_store_dangerous_goods,
    COALESCE(sum(threaten_safety_fire_hazards), 0) AS threaten_safety_fire_hazards";
                        query = @"
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        cs_type = "and type =" + type_cs;
                        type_cs = @",		
(
COALESCE(count(DISTINCT(case when project_name='use_electric_bicycle' then t.house_id end)),0 )+
COALESCE(count(DISTINCT(case when project_name='use_bottled_liquefied_gas' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='use_stacked_items' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='use_burglar_mesh' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='use_ceiling' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='is_completely_isolated' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='use_flammable_materials' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='unauthorized_electrical_connect' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='not_enough_exits' then t.house_id end) ),0 )+ 
COALESCE(count(DISTINCT(case when project_name='use_flammable_insulation_materials' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='use_flammable_dangerous_goods' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='above_three_floor_self' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='fire_service_damaged' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='use_store_dangerous_goods' then t.house_id end) ),0 )+
COALESCE(count(DISTINCT(case when project_name='threaten_safety_fire_hazards' then t.house_id end) ),0 )
) AS sumall,
COALESCE(count(DISTINCT(case when project_name='use_electric_bicycle' then t.house_id end) ),0 ) as use_electric_bicycle,
COALESCE(count(DISTINCT(case when project_name='use_bottled_liquefied_gas' then t.house_id end) ),0 ) as use_bottled_liquefied_gas,
COALESCE(count(DISTINCT(case when project_name='use_stacked_items' then t.house_id end) ),0 ) as use_stacked_items,
COALESCE(count(DISTINCT(case when project_name='use_burglar_mesh' then t.house_id end) ),0 ) as use_burglar_mesh,
COALESCE(count(DISTINCT(case when project_name='use_ceiling' then t.house_id end) ),0 ) as use_ceiling,
COALESCE(count(DISTINCT(case when project_name='is_completely_isolated' then t.house_id end) ),0 ) as is_completely_isolated,
COALESCE(count(DISTINCT(case when project_name='use_flammable_materials' then t.house_id end) ),0 ) as use_flammable_materials,
COALESCE(count(DISTINCT(case when project_name='unauthorized_electrical_connect' then t.house_id end) ),0 ) as unauthorized_electrical_connect,
COALESCE(count(DISTINCT(case when project_name='not_enough_exits' then t.house_id end) ),0 ) as not_enough_exits,
COALESCE(count(DISTINCT(case when project_name='use_flammable_insulation_materials' then t.house_id end) ),0 ) as use_flammable_insulation_materials,
COALESCE(count(DISTINCT(case when project_name='use_flammable_dangerous_goods' then t.house_id end) ),0 ) as use_flammable_dangerous_goods,
COALESCE(count(DISTINCT(case when project_name='above_three_floor_self' then t.house_id end) ),0 ) as above_three_floor_self,
COALESCE(count(DISTINCT(case when project_name='fire_service_damaged' then t.house_id end) ),0 ) as fire_service_damaged,
COALESCE(count(DISTINCT(case when project_name='use_store_dangerous_goods' then t.house_id end) ),0 ) as use_store_dangerous_goods,
COALESCE(count(DISTINCT(case when project_name='threaten_safety_fire_hazards' then t.house_id end) ),0 ) as threaten_safety_fire_hazards ";
                    }
                    else if (type_cs == "3")
                    {
                        groupquery = @" 
    COALESCE(sum(sumall), 0) AS sumall,
    COALESCE(sum(use_electric_bicycle), 0) AS use_electric_bicycle,
    COALESCE(sum(use_bottled_liquefied_gas), 0) AS use_bottled_liquefied_gas,
    COALESCE(sum(use_stacked_items), 0) AS use_stacked_items,
    COALESCE(sum(use_burglar_mesh), 0) AS use_burglar_mesh,
    COALESCE(sum(use_ceiling), 0) AS use_ceiling,
    COALESCE(sum(is_completely_isolated), 0) AS is_completely_isolated,
    COALESCE(sum(use_flammable_materials), 0) AS use_flammable_materials,
    COALESCE(sum(unauthorized_electrical_connect), 0) AS unauthorized_electrical_connect,
    COALESCE(sum(not_enough_exits), 0) AS not_enough_exits,
    COALESCE(sum(use_flammable_insulation_materials), 0) AS use_flammable_insulation_materials,
    COALESCE(sum(use_flammable_dangerous_goods), 0) AS use_flammable_dangerous_goods,
    COALESCE(sum(above_three_floor_self), 0) AS above_three_floor_self,
    COALESCE(sum(fire_service_damaged), 0) AS fire_service_damaged,
    COALESCE(sum(use_store_dangerous_goods), 0) AS use_store_dangerous_goods,
    COALESCE(sum(charging_facilities_no_standard), 0) AS charging_facilities_no_standard,
    COALESCE(sum(threaten_safety_fire_hazards), 0) AS threaten_safety_fire_hazards";
                        query = @" 
    COALESCE(tmp.sumall, 0) AS sumall,
    COALESCE(tmp.use_electric_bicycle, 0) AS use_electric_bicycle,
    COALESCE(tmp.use_bottled_liquefied_gas, 0) AS use_bottled_liquefied_gas,
    COALESCE(tmp.use_stacked_items, 0) AS use_stacked_items,
    COALESCE(tmp.use_burglar_mesh, 0) AS use_burglar_mesh,
    COALESCE(tmp.use_ceiling, 0) AS use_ceiling,
    COALESCE(tmp.is_completely_isolated, 0) AS is_completely_isolated,
    COALESCE(tmp.use_flammable_materials, 0) AS use_flammable_materials,
    COALESCE(tmp.unauthorized_electrical_connect, 0) AS unauthorized_electrical_connect,
    COALESCE(tmp.not_enough_exits, 0) AS not_enough_exits,
    COALESCE(tmp.use_flammable_insulation_materials, 0) AS use_flammable_insulation_materials,
    COALESCE(tmp.use_flammable_dangerous_goods, 0) AS use_flammable_dangerous_goods,
    COALESCE(tmp.above_three_floor_self, 0) AS above_three_floor_self,
    COALESCE(tmp.fire_service_damaged, 0) AS fire_service_damaged,
    COALESCE(tmp.use_store_dangerous_goods, 0) AS use_store_dangerous_goods,
    COALESCE(tmp.charging_facilities_no_standard, 0) AS charging_facilities_no_standard,
    COALESCE(tmp.threaten_safety_fire_hazards, 0) AS threaten_safety_fire_hazards";
                        type_cs = @",(
COALESCE(count(DISTINCT(case when project_name = 'use_electric_bicycle' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_bottled_liquefied_gas' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_stacked_items' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_burglar_mesh' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_ceiling' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'is_completely_isolated' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_materials' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'unauthorized_electrical_connect' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'not_enough_exits' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_insulation_materials' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_dangerous_goods' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'above_three_floor_self' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'fire_service_damaged' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'use_store_dangerous_goods' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'charging_facilities_no_standard' then t.house_id end)), 0) +
COALESCE(count(DISTINCT(case when project_name = 'threaten_safety_fire_hazards' then t.house_id end)), 0)
) AS sumall,
COALESCE(count(DISTINCT(case when project_name = 'use_electric_bicycle' then t.house_id end)), 0 ) as use_electric_bicycle,
COALESCE(count(DISTINCT(case when project_name = 'use_bottled_liquefied_gas' then t.house_id end)), 0) as use_bottled_liquefied_gas,
COALESCE(count(DISTINCT(case when project_name = 'use_stacked_items' then t.house_id end)), 0) as use_stacked_items,
COALESCE(count(DISTINCT(case when project_name = 'use_burglar_mesh' then t.house_id end)), 0) as use_burglar_mesh,
COALESCE(count(DISTINCT(case when project_name = 'use_ceiling' then t.house_id end)), 0) as use_ceiling,
COALESCE(count(DISTINCT(case when project_name = 'is_completely_isolated' then t.house_id end)), 0) as is_completely_isolated,
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_materials' then t.house_id end)), 0) as use_flammable_materials,
COALESCE(count(DISTINCT(case when project_name = 'unauthorized_electrical_connect' then t.house_id end)), 0) as unauthorized_electrical_connect,
COALESCE(count(DISTINCT(case when project_name = 'not_enough_exits' then t.house_id end)), 0) as not_enough_exits,
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_insulation_materials' then t.house_id end)), 0) as use_flammable_insulation_materials,
COALESCE(count(DISTINCT(case when project_name = 'use_flammable_dangerous_goods' then t.house_id end)), 0) as use_flammable_dangerous_goods,
COALESCE(count(DISTINCT(case when project_name = 'above_three_floor_self' then t.house_id end)), 0) as above_three_floor_self,
COALESCE(count(DISTINCT(case when project_name = 'fire_service_damaged' then t.house_id end)), 0) as fire_service_damaged,
COALESCE(count(DISTINCT(case when project_name = 'use_store_dangerous_goods' then t.house_id end)), 0) as use_store_dangerous_goods,
COALESCE(count(DISTINCT(case when project_name = 'charging_facilities_no_standard' then t.house_id end)), 0) as charging_facilities_no_standard,
COALESCE(count(DISTINCT(case when project_name = 'threaten_safety_fire_hazards' then t.house_id end)), 0) as threaten_safety_fire_hazards";
                    }
                    else
                    {
                        return new RespRet<List<object>>(false, "专项类型错误");
                    }
                }

                //type_yh = "1";
                if (string.IsNullOrEmpty(type_yh))
                {
                    return new RespRet<List<object>>(false, "隐患类型不能为空");
                }
                string isxcyh = "";
                string str = "";
                if (type_yh == "0")
                {
                    str = "yhfx_time";
                }
                else
                {
                    str = "yhxc_time";
                }

                if (type_yh == "0")
                {
                    type_yh = " and yhfx_time is not null ";
                }
                else if (type_yh == "1")
                {
                    isxcyh = "1";
                    type_yh = @$" and   ( t.yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time <'2023/3/16 0:00:00' ) ";
                }
                else if (type_yh == "2")
                {
                    //type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time between '{StartTime}' and '{EndTime}') ";
                    type_yh = $"and (yhxc_time is  null or yhxc_time>'{EndTime}') and(t.yhfx_time <= '{EndTime}') and yhfx_time<'2023/3/16 0:00:00' ";
                    str = "2";
                }
                //时间区间查询
                string querydate = "";
                if (StartTime != null && EndTime != null)
                {
                    querydate = $" and(t.{str} between '{StartTime}' and '{EndTime}' )";
                }
                //如果是剩余 
                if (str == "2")
                {
                    querydate = "";
                }

                string zx = "";
                string dccode = "";
                if (string.IsNullOrEmpty(type_zx))
                {
                    return new RespRet<List<object>>(false, "专项类型不能为空");
                }
                else
                {
                    if (type_zx == "777")
                    {

                        zx = @" and check777 = '1'";
                    }
                    else if (type_zx == "108")
                    {
                        zx = @" and check108 = '1'";
                    }
                    else if (type_zx == "0")
                    {
                        zx = "";
                    }
                }
                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<List<object>>(false, "用户名不存在");
                }
                // var curuserDto = _mapper.Map<UserDto>(curuser);

                string codewhere = "";
                //根据用户角色过滤
                if (curuser.RoleType > 1)
                {
                    if (curuser.RoleType == 3)
                    {
                        JObject obj = JObject.Parse(curuser.District);
                        string RegionCode = (string)obj["RegionCode"];
                        codewhere = $"and xzqdm='{RegionCode}'";
                    }
                    else if (curuser.RoleType == 4)
                    {
                        JObject obj = JObject.Parse(curuser.District);
                        string RegionCode = (string)obj["RegionCode"];
                        codewhere = $"and town='{RegionCode}'";

                    }
                    else if (curuser.RoleType == 5)
                    {
                        JObject obj = JObject.Parse(curuser.District);
                        string RegionCode = (string)obj["RegionCode"];
                        codewhere = $"and village='{RegionCode}'";

                    }
                }

                string xzqdm = "xzqdm";
                string groupname = "";
                string getdatabycode = "";
                if (groupbyLever == "0")
                {
                    groupname = ") a group by xzqdm";
                    if (groupbyLever_code != null)

                        getdatabycode = $"and xzqdm='{groupbyLever_code}'"; if (groupbyLever_code == "110000")
                    {
                        getdatabycode = " ";
                    }
                }
                else if (groupbyLever == "1")
                {
                    groupname = ") a group by town";
                    if (groupbyLever_code != null)
                    {
                        getdatabycode = $"and xzqdm='{groupbyLever_code}'";
                    }
                    xzqdm = "town";
                }
                else if (groupbyLever == "2")
                {
                    xzqdm = "village";
                    groupname = ") a group by village";
                    if (groupbyLever_code != null)
                    {
                        getdatabycode = $"and town='{groupbyLever_code}'";
                    }
                }
                else
                {
                    return new RespRet<List<object>>(false, "分组格式不正确");
                }

                string querystr = @$" select max(village) village,max({xzqdm}) xzqdm,COALESCE(sum(ypc_sl), 0)as ypc_sl,
     max(villagename) AS villagename, max(xzqdmname) xzqdmname, max(town) town, max(townname)townname,
   {groupquery}
 from(";
                sqlstr = @$"{querystr} select  dc.village,COALESCE(tmp.ypc_sl, 0)as ypc_sl,
      dc.villagename AS villagename,
          dc.xzqdm,dc.xzqdmname,dc.town,dc.townname,
         {query}  from
(select village, villagename,xzqdm,xzqdmname,town,townname from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171') {codewhere} {getdatabycode} {zx} GROUP BY village, villagename,xzqdm,xzqdmname,town,townname order by village) dc
      left join
      (
      select
 count(Distinct (t.fwbh)) as ypc_sl,
     h.village,h.town,h.xzqdm {type_cs}
      from zm_xf_pc_detailed t,
      zm_buildings_layer h
      WHERE t.fwbh::text = h.fwbh::text  AND(h.is_delete IS NULL OR h.is_delete <> 1)
      {type_yh} {cs_type} {querydate}  GROUP BY  h.village,h.xzqdm,h.town   ) tmp  on dc.village = tmp.village" + groupname + "  ORDER BY village";
                //防止注入
                if (sqlstr.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sqlstr.Contains("update ", StringComparison.OrdinalIgnoreCase))
                {
                    return new RespRet<List<object>>(false, "不符合规范，禁止执行");
                }

                if (isxcyh == "1")
                {
                    if (groupbyLever == "0")
                    {
                        sqlstr = @$"select b.*,case when  a.cl_scfw315 is not null then a.cl_scfw315 else 0 end as ypc_sl from(select xzqdm,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and house_id not in ( select DISTINCT(house_id) from ( select xzqdm,house_id,
case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<'2023/3/16 0:00:00'
GROUP BY xzqdm,house_id) and yhxc_time >'{EndTime}' and yhfx_time <'2023-03-15 23:59:59' then  ts.house_id end cl_scfw315
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx} )
)a where cl_scfw315 is not null)  and yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315 --315前消除隐患房屋 
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')   {zx} )
GROUP BY xzqdm)  a RIGHT JOIN ({sqlstr}) b on a.xzqdm=b.xzqdm";

                    }
                    if (groupbyLever == "1")
                    {
                        sqlstr = @$"select b.*,case when  a.cl_scfw315 is not null then a.cl_scfw315 else 0 end as ypc_sl from(select xzqdm,town,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and house_id not in ( select DISTINCT(house_id) from ( select xzqdm,house_id,
case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<'2023/3/16 0:00:00'
GROUP BY xzqdm,house_id) and yhxc_time >'{EndTime}' and yhfx_time <'2023-03-15 23:59:59' then  ts.house_id end cl_scfw315
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx} )
)a where cl_scfw315 is not null)  and yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315 --315前消除隐患房屋 
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')   {zx} )
GROUP BY xzqdm,town)  a RIGHT JOIN ({sqlstr}) b on a.town=b.town";
                    }
                    if (groupbyLever == "2")
                    {
                        sqlstr = @$"select b.*,case when  a.cl_scfw315 is not null then a.cl_scfw315 else 0 end as ypc_sl from(select xzqdm,town,village,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and house_id not in ( select DISTINCT(house_id) from ( select xzqdm,house_id,
case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx}  )  and yhxc_time is null  and yhfx_time<'2023/3/16 0:00:00'
GROUP BY xzqdm,house_id) and yhxc_time >'{EndTime}' and yhfx_time <'2023-03-15 23:59:59' then  ts.house_id end cl_scfw315
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {zx} )
)a where cl_scfw315 is not null)  and yhxc_time between '{StartTime}' and '{EndTime}' and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315 --315前消除隐患房屋 
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')   {zx} )
GROUP BY xzqdm,town,village)  a RIGHT JOIN ({sqlstr}) b on a.village=b.village";
                    }
                }



                var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();
                return new RespRet<List<object>>(true, "Ok", datas);
            }
            catch (Exception ex)
            {

                return "异常，请检查参数后重试" + sqlstr;
            }

        }





        /// <summary>
        /// 总项数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet("admin/custom-function/Get777108Data")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public Object Get777108Data([FromQuery] string type, [FromQuery] string groupbyLever, [FromQuery] string groupbyLever_code)
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<object>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<List<object>>(false, "用户名不存在");
            }
            if (type == "777")
            {
                type = "and check777 = '1'";
            }
            else if (type == "108")
            {
                type = "and check108 = '1'";
            }
            else if (type == "107")
            {
                type = "and check107 = '1'";
            }
            else
            {
                type = " ";
            }
            string sql = "";

            string codewhere = "";
            //根据用户角色过滤
            if (curuser.RoleType > 1)
            {
                if (curuser.RoleType == 3)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and xzqdm='{RegionCode}'";
                }
                else if (curuser.RoleType == 4)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and town='{RegionCode}'";
                    if (groupbyLever == "0" || groupbyLever == "1")
                    {
                        groupbyLever = "2";
                    }
                }
                else if (curuser.RoleType == 5)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and village='{RegionCode}'";
                    groupbyLever = "2";
                }
            }

            if (string.IsNullOrEmpty(groupbyLever))
            {
                return new RespRet<List<object>>(false, "分组等级必须传递");
            }
            if (groupbyLever == "0")
            {
                if (!string.IsNullOrEmpty(groupbyLever_code))
                {
                    groupbyLever_code = $"and xzqdm ='{groupbyLever_code}'";
                }
                sql = @$"select  dc.xzqdm AS xzqdm,
      dc.xzqdmname AS xzqdmname, 
case when tmp.cl_scfw315 is null then   0 else tmp.cl_scfw315 end ,
case when tmp.cl_syfw315 is null then   0 else tmp.cl_syfw315 end ,
case when tmp.xyyhfw is null then   0 else tmp.xyyhfw end ,
   case when tmp.xz is null then   0 else tmp.xz end ,
	case when tmp.xc_315 is null  then 0 else tmp.xc_315 end ,
	case when tmp.xc_all is null then 0 else tmp.xc_all end ,
	case when tmp.sy_315 is null then 0 else tmp.sy_315 end ,
	case when tmp.sy_all is null then 0 else tmp.sy_all end ,
	case when tmp.cl_fx315  is null then 0 else tmp.cl_fx315 end ,
	case when tmp.cl_xc315  is null then 0 else tmp.cl_xc315 end,
	case when tmp.cl_sy315  is null then 0 else tmp.cl_sy315 end ,
	case when tmp.xchouse_all  is null then 0 else tmp.xchouse_all end ,
	case when tmp.xchouse_315  is null then 0 else tmp.xchouse_315 end,
	case when tmp.fxhouse315  is null then 0 else tmp.fxhouse315 end
     from
(select xzqdm, xzqdmname from zm_department_xf_2023 where regional_level = '7' {codewhere} and xzqdm not in ('110101','110102','110171') {groupbyLever_code} {type} GROUP BY xzqdm, xzqdmname order by xzqdm) dc
      left join
      (

select a.*, b.xchouse_all, b.xchouse_315, c.fxhouse315 from
(
select xzqdm,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')    )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315, --315前消除隐患房屋
count(DISTINCT((case when yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_syfw315, --存量315前剩余房屋
count(DISTINCT((case when yhxc_time is null then  ts.house_id end))) xyyhfw, --现有隐患房屋  
sum(case when ts.yhfx_time > '2023-03-15 23:59:59' then 1 else 0 end ) as xz, --新增
sum(case when ts.yhfx_time <= '2023-03-15 23:59:59'  and   ts.yhxc_time > '2023-03-15 23:59:59' then 1 else 0 end ) as xc_315,--隐患消除（315前存量）
sum(case when ts.yhfx_time > '2023-03-15 23:59:59'  and    ts.yhxc_time > '2023-03-15 23:59:59'  then 1 else 0 end ) as xc_all,  --隐患消除数
sum(case when   ts.yhxc_time is null then 1 else 0 end ) as sy_315,--剩余隐患数（315前存量）
sum(case when  ts.yhxc_time is null  and  ts.yhfx_time > '2023-03-15 23:59:59'  then 1 else 0 end ) as sy_all,  --剩余隐患数,

sum(case when ts.yhfx_time < '2023-03-15 23:59:59'    then 1 else 0 end ) as cl_fx315, --发现隐患数(存量)
sum(case when ts.yhxc_time is not null  and ts.yhfx_time<='2023-03-15 23:59:59'    then 1 else 0 end) as cl_xc315, --消除隐患数(存量)
sum(case when ts.yhfx_time < '2023-03-15 23:59:59'  and(ts.yhxc_time is null) then 1 else 0 end) as cl_sy315 --剩余隐患数(存量)
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')  {type} )
GROUP BY xzqdm

)a,
(
select xzqdm,
sum(case when ta.maxtime > '2023-03-15 23:59:59'  then 1 else 0 end ) as xchouse_all,--隐患消除栋
sum(case when ta.maxtime > '2023-03-15 23:59:59' and ta.mintime < '2023-03-15 23:59:59'  then 1 else 0 end ) as xchouse_315--隐患消除栋（315前存量）

from(
select distinct house_id, xzqdm, max(yhxc_time) as maxtime, min(yhfx_time) as mintime from zm_xf_pc_detailed where house_id  not in (select house_id from zm_xf_pc_detailed where yhxc_time is null )  and village in (select region_code from zm_department_xf_2023 where regional_level = '7'  {type}) GROUP BY house_id,xzqdm
) ta
GROUP BY xzqdm
)b
,
(
select xzqdm,
count(1) as fxhouse315
from(
select distinct house_id, xzqdm, max(yhxc_time) as maxtime  from zm_xf_pc_detailed where yhfx_time <= '2023-03-15 23:59:59'    and  village in (select region_code from zm_department_xf_2023 where regional_level = '7'    {type}) GROUP BY house_id,xzqdm
) ta
GROUP BY xzqdm
) 
c

where a.xzqdm = b.xzqdm and a.xzqdm = c.xzqdm
order by  a.xzqdm
) tmp

on dc.xzqdm = tmp.xzqdm";
            }
            else if (groupbyLever == "1")
            {
                if (!string.IsNullOrEmpty(groupbyLever_code))
                {
                    groupbyLever_code = $"and xzqdm ='{groupbyLever_code}'";
                }
                sql = @$"select  dc.town AS xzqdm,dc.town,dc.townname,
      dc.xzqdmname AS xzqdmname,  
case when tmp.cl_scfw315 is null then   0 else tmp.cl_scfw315 end ,
case when tmp.cl_syfw315 is null then   0 else tmp.cl_syfw315 end ,
case when tmp.xyyhfw is null then   0 else tmp.xyyhfw end ,
  case when tmp.xz is null then   0 else tmp.xz end ,
	case when tmp.xc_315 is null  then 0 else tmp.xc_315 end ,
	case when tmp.xc_all is null then 0 else tmp.xc_all end ,
	case when tmp.sy_315 is null then 0 else tmp.sy_315 end ,
	case when tmp.sy_all is null then 0 else tmp.sy_all end ,
	case when tmp.cl_fx315  is null then 0 else tmp.cl_fx315 end ,
	case when tmp.cl_xc315  is null then 0 else tmp.cl_xc315 end,
	case when tmp.cl_sy315  is null then 0 else tmp.cl_sy315 end ,
	case when tmp.xchouse_all  is null then 0 else tmp.xchouse_all end ,
	case when tmp.xchouse_315  is null then 0 else tmp.xchouse_315 end,
	case when tmp.fxhouse315  is null then 0 else tmp.fxhouse315 end
     from
(select xzqdm, xzqdmname, town, townname from zm_department_xf_2023 where regional_level = '7' {codewhere}{groupbyLever_code} and xzqdm not in ('110101','110102','110171')   {type}
                GROUP BY xzqdm,town,townname ,xzqdmname order by xzqdm, town) dc
left join
(

select a.*, b.xchouse_all, b.xchouse_315, c.fxhouse315 from
(
select xzqdm, town,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')    )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315, --315前消除隐患房屋
count(DISTINCT((case when yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_syfw315, --存量315前剩余房屋
count(DISTINCT((case when yhxc_time is null then  ts.house_id end))) xyyhfw, --现有隐患房屋 
sum(case when ts.yhfx_time > '2023-03-15 23:59:59' then 1 else 0 end ) as xz, --新增
sum(case when ts.yhfx_time <= '2023-03-15 23:59:59'  and   ts.yhxc_time > '2023-03-15 23:59:59' then 1 else 0 end ) as xc_315,--隐患消除（315前存量）
sum(case when ts.yhfx_time > '2023-03-15 23:59:59'  and    ts.yhxc_time > '2023-03-15 23:59:59'  then 1 else 0 end ) as xc_all,  --隐患消除数
sum(case when ts.yhxc_time is null then 1 else 0 end ) as sy_315,--剩余隐患数（315前存量）
sum(case when  ts.yhxc_time is null  and  ts.yhfx_time > '2023-03-15 23:59:59'  then 1 else 0 end ) as sy_all,  --剩余隐患数,

sum(case when ts.yhfx_time < '2023-03-15 23:59:59'    then 1 else 0 end ) as cl_fx315, --发现隐患数(存量)
sum(case when ts.yhxc_time is not null  and ts.yhfx_time<='2023-03-15 23:59:59'    then 1 else 0 end) as cl_xc315, --消除隐患数(存量)
sum(case when ts.yhfx_time < '2023-03-15 23:59:59'  and(ts.yhxc_time is null) then 1 else 0 end) as cl_sy315 --剩余隐患数(存量)
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7'  and xzqdm not in ('110101','110102','110171')  {type} )
GROUP BY xzqdm,town

)a,
(
select town,sum(case when xchouse_all is null then 0 else xchouse_all end)xchouse_all,sum(case when xchouse_315 is null then 0 else xchouse_315 end)xchouse_315 from ( select zm.town,xchouse_all,xchouse_315 from(select * from zm_department_xf_2023  where regional_level='7' {type}   )zm
left join
(select xzqdm,town,village,
sum(case when ta.maxtime > '2023-03-15 23:59:59'  then 1 else 0 end ) as xchouse_all,--隐患消除栋
sum(case when ta.maxtime > '2023-03-15 23:59:59' and ta.mintime < '2023-03-15 23:59:59'  then 1 else 0 end ) as xchouse_315--隐患消除栋（315前存量）
from(
select distinct house_id,town, xzqdm,village, max(yhxc_time) as maxtime, min(yhfx_time) as mintime from zm_xf_pc_detailed where house_id  not in (select house_id from zm_xf_pc_detailed where yhxc_time is null )  GROUP BY house_id,xzqdm,town,village
) ta
GROUP BY xzqdm,town,village) house on zm.region_code=house.village)grouptown group by town
)b
,
(
select r.fxhouse315,zm.xzqdm,zm.town from (select DISTINCT(town),xzqdm from zm_department_xf_2023 where 1=1 {type} ) zm left join ( select xzqdm,town,
count(1) as fxhouse315
from(
select distinct house_id,max(yhfx_time) yhfx_time,cz.xzqdm,cz.town, max(yhxc_time) as maxtime  from zm_xf_pc_detailed zm right join zm_department_xf_2023 cz on zm.village=cz.village where cz.xzqdm not in ('110101','110102','110171')  and yhfx_time <= '2023-03-15 23:59:59' {type}   GROUP BY house_id,cz.xzqdm,cz.town
) ta
GROUP BY xzqdm,town ) r on zm.town=r.town 
) 
c
where a.town = b.town and a.town = c.town
order by  a.town
) tmp

on dc.town = tmp.town";
            }
            else if (groupbyLever == "2")
            {
                if (!string.IsNullOrEmpty(groupbyLever_code))
                {
                    groupbyLever_code = $"and town ='{groupbyLever_code}'";
                }
                sql = @$"select  dc.village AS xzqdm,dc.town,dc.townname,dc.village,dc. villagename,
      dc.xzqdmname AS xzqdmname, 
case when tmp.cl_scfw315 is null then   0 else tmp.cl_scfw315 end ,
case when tmp.cl_syfw315 is null then   0 else tmp.cl_syfw315 end ,
case when tmp.xyyhfw is null then   0 else tmp.xyyhfw end ,
 case when tmp.xz is null then   0 else tmp.xz end ,
	case when tmp.xc_315 is null  then 0 else tmp.xc_315 end ,
	case when tmp.xc_all is null then 0 else tmp.xc_all end ,
	case when tmp.sy_315 is null then 0 else tmp.sy_315 end ,
	case when tmp.sy_all is null then 0 else tmp.sy_all end ,
	case when tmp.cl_fx315  is null then 0 else tmp.cl_fx315 end ,
	case when tmp.cl_xc315  is null then 0 else tmp.cl_xc315 end,
	case when tmp.cl_sy315  is null then 0 else tmp.cl_sy315 end ,
	case when tmp.xchouse_all  is null then 0 else tmp.xchouse_all end ,
	case when tmp.xchouse_315  is null then 0 else tmp.xchouse_315 end,
	case when tmp.fxhouse315  is null then 0 else tmp.fxhouse315 end
     from
(select xzqdm, village,villagename,xzqdmname,town,townname from zm_department_xf_2023 where regional_level = '7'{codewhere} {groupbyLever_code} and xzqdm not in ('110101','110102','110171') {type} GROUP BY xzqdm,village,villagename,town,townname ,xzqdmname order by xzqdm,town) dc
      left join
      (

select a.*, b.xchouse_all, b.xchouse_315, c.fxhouse315 from
(
select xzqdm,town,village,
count(DISTINCT((case when yhxc_time is not null and house_id not in(select 
house_id
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171')    )  and yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59'
GROUP BY xzqdm,house_id) and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_scfw315, --315前消除隐患房屋
count(DISTINCT((case when yhxc_time is null  and yhfx_time<='2023-03-15 23:59:59' then  ts.house_id end))) cl_syfw315, --存量315前剩余房屋
count(DISTINCT((case when yhxc_time is null then  ts.house_id end))) xyyhfw, --现有隐患房屋 
sum(case when ts.yhfx_time > '2023-03-15 23:59:59' then 1 else 0 end ) as xz, --新增
sum(case when ts.yhfx_time <= '2023-03-15 23:59:59'  and   ts.yhxc_time > '2023-03-15 23:59:59' then 1 else 0 end ) as xc_315,--隐患消除（315前存量）
sum(case when ts.yhfx_time > '2023-03-15 23:59:59'  and    ts.yhxc_time > '2023-03-15 23:59:59'  then 1 else 0 end ) as xc_all,  --隐患消除数
sum(case when ts.yhxc_time is null then 1 else 0 end ) as sy_315,--剩余隐患数（315前存量）
sum(case when  ts.yhxc_time is null  and  ts.yhfx_time > '2023-03-15 23:59:59'  then 1 else 0 end ) as sy_all,  --剩余隐患数,

sum(case when ts.yhfx_time < '2023-03-15 23:59:59'    then 1 else 0 end ) as cl_fx315, --发现隐患数(存量)
sum(case when ts.yhxc_time is not null  and ts.yhfx_time<='2023-03-15 23:59:59'    then 1 else 0 end) as cl_xc315, --消除隐患数(存量)
sum(case when ts.yhfx_time < '2023-03-15 23:59:59'  and(ts.yhxc_time is null) then 1 else 0 end) as cl_sy315 --剩余隐患数(存量)
from zm_xf_pc_detailed ts where village in (select region_code from zm_department_xf_2023 where regional_level = '7' and xzqdm not in ('110101','110102','110171') {type} )
GROUP BY xzqdm,town,village

)a,
(
select * from(select region_code from zm_department_xf_2023  where regional_level='7' {type} and xzqdm not in ('110101','110102','110171')  )zm
left join
(select xzqdm,town,village,
sum(case when ta.maxtime > '2023-03-15 23:59:59'  then 1 else 0 end ) as xchouse_all,--隐患消除栋
sum(case when ta.maxtime > '2023-03-15 23:59:59' and ta.mintime < '2023-03-15 23:59:59'  then 1 else 0 end ) as xchouse_315--隐患消除栋（315前存量）
from(
select distinct house_id,town, xzqdm,village, max(yhxc_time) as maxtime, min(yhfx_time) as mintime from zm_xf_pc_detailed where house_id  not in (select house_id from zm_xf_pc_detailed where yhxc_time is null )  GROUP BY house_id,xzqdm,town,village
) ta
GROUP BY xzqdm,town,village) house on zm.region_code=house.village   
)b
,
(
select xzqdm,town,village,
count(1) as fxhouse315
from(
select distinct house_id, xzqdm,town,village, max(yhxc_time) as maxtime  from zm_xf_pc_detailed where yhfx_time <= '2023-03-15 23:59:59'    and  village in (select region_code from zm_department_xf_2023 where regional_level = '7'  and xzqdm not in ('110101','110102','110171')  {type}) GROUP BY house_id,xzqdm,town,village
) ta
GROUP BY xzqdm,town,village
) 
c
where a.village = b.region_code and a.village = c.village
order by  a.village
) tmp

on dc.village = tmp.village";
            }
            //防止注入
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
            || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
            || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<List<object>>(false, "不符合规范，禁止执行");
            }
            var datas = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            return new RespRet<List<object>>(true, "Ok", datas);
        }

        /// <summary>
        /// 村庄设施汇总
        /// </summary>
        /// <param name="type_zx"></param>
        /// <param name="groupbyLever"></param>
        /// <param name="groupbyLever_code"></param>
        /// <returns></returns>

        [HttpGet("admin/custom-function/VillageFacilitySummary")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<List<object>> VillageFacilitySummary([FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] string groupbyLever_code)
        {
            if (string.IsNullOrWhiteSpace(groupbyLever))
            {
                return new RespRet<List<object>>(true, "分组等级不能为空");
            }
            if (string.IsNullOrWhiteSpace(groupbyLever_code))
            {
                return new RespRet<List<object>>(true, "行政区代码不能为空");
            }
            if (string.IsNullOrWhiteSpace(type_zx))
            {
                return new RespRet<List<object>>(true, "专项类型不能为空");
            }
            //专项条件
            if (type_zx == "0")
            {
                type_zx = " ";
            }
            else if (type_zx == "777")
            {
                type_zx = " and  cz.check777=1 ";
            }
            else if (type_zx == "108")
            {
                type_zx = " and cz.check108=1 ";
            }

            string sql = "";
            if (groupbyLever == "2")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and country='{groupbyLever_code}'";
                }
                sql = @$"SELECT zm.village,village_name villagename,
max(jd.region_name) townname ,
max(qx.region_name) xzqdmname,
max(jd.region_code) towncode,
max(cz.region_code) xzqdm ,
case when sum(self_built_houses_area_number) is null then 0 else sum(self_built_houses_area_number)  end self_built_houses_area_number,
case when sum(fire_lanes_number) is null then 0 else sum(fire_lanes_number)  end fire_lanes_number,
case when sum(fire_pool_number) is null then 0 else sum(fire_pool_number) end fire_pool_number,
case when sum(charging_facilities_number) is null then 0 else sum(charging_facilities_number) end charging_facilities_number,
case when sum(outdoor_fire_hydrant_number) is null then 0 else sum(outdoor_fire_hydrant_number) end outdoor_fire_hydrant_number,
case when sum(fire_water_crane_number) is null then 0 else sum(fire_water_crane_number) end fire_water_crane_number,
case when sum(fire_brigade_number) is null then 0 else sum(fire_brigade_number) end fire_brigade_number,
case when sum(fire_fighter_number) is null then 0 else sum(fire_fighter_number) end fire_fighter_number,
case when sum(fire_truck_number) is null then 0 else sum(fire_truck_number) end fire_truck_number,
case when sum(fire_station_number) is null then 0 else sum(fire_station_number) end fire_station_number,
case when sum(fire_station_personnel_number) is null then 0 else sum(fire_station_personnel_number) end fire_station_personnel_number,
case when sum(fire_station_truck_number) is null then 0 else sum(fire_station_truck_number) end fire_station_truck_number,
case when sum(electric_bicycle_number) is null then 0 else sum(electric_bicycle_number) end electric_bicycle_number,
case when sum(self_built_rental_house_number) is null then 0 else sum(self_built_rental_house_number) end self_built_rental_house_number
 FROM  zm_village_fire_safety zm,zm_department_xf_2023 cz,zm_department_xf_2023 jd,zm_department_xf_2023 qx
 where zm.village=cz.region_code and jd.region_code=zm.country and zm.county=qx.region_code and cz.regional_level='7' {groupbyLever_code} {type_zx} and zm.is_delete is null GROUP BY zm.village,village_name  order by zm.village";
            }
            if (groupbyLever == "1")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and county='{groupbyLever_code}'";
                }
                sql = @$"SELECT 
max(jd.region_name) townname ,
max(qx.region_name) xzqdmname,
max(jd.region_code) towncode,
max(jd.region_code)xzqdm ,
case when sum(self_built_houses_area_number) is null then 0 else sum(self_built_houses_area_number)  end self_built_houses_area_number,
case when sum(fire_lanes_number) is null then 0 else sum(fire_lanes_number)  end fire_lanes_number,
case when sum(fire_pool_number) is null then 0 else sum(fire_pool_number) end fire_pool_number,
case when sum(charging_facilities_number) is null then 0 else sum(charging_facilities_number) end charging_facilities_number,
case when sum(outdoor_fire_hydrant_number) is null then 0 else sum(outdoor_fire_hydrant_number) end outdoor_fire_hydrant_number,
case when sum(fire_water_crane_number) is null then 0 else sum(fire_water_crane_number) end fire_water_crane_number,
case when sum(fire_brigade_number) is null then 0 else sum(fire_brigade_number) end fire_brigade_number,
case when sum(fire_fighter_number) is null then 0 else sum(fire_fighter_number) end fire_fighter_number,
case when sum(fire_truck_number) is null then 0 else sum(fire_truck_number) end fire_truck_number,
case when sum(fire_station_number) is null then 0 else sum(fire_station_number) end fire_station_number,
case when sum(fire_station_personnel_number) is null then 0 else sum(fire_station_personnel_number) end fire_station_personnel_number,
case when sum(fire_station_truck_number) is null then 0 else sum(fire_station_truck_number) end fire_station_truck_number,
case when sum(electric_bicycle_number) is null then 0 else sum(electric_bicycle_number) end electric_bicycle_number,
case when sum(self_built_rental_house_number) is null then 0 else sum(self_built_rental_house_number) end self_built_rental_house_number
 FROM  zm_village_fire_safety zm,zm_department_xf_2023 cz,zm_department_xf_2023 jd,zm_department_xf_2023 qx
 where zm.village=cz.region_code and jd.region_code=zm.country {groupbyLever_code} and zm.county=qx.region_code and cz.regional_level='7'  {type_zx}  and zm. is_delete is null GROUP BY jd.region_code,jd,jd.region_name order by jd.region_code";
            }

            if (groupbyLever == "0")
            {
                if (groupbyLever_code == "110000")
                {
                    groupbyLever_code = " ";
                }
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and county='{groupbyLever_code}'";
                }

                sql = @$"SELECT 
max(qx.region_name) xzqdmname,
max(qx.region_code)xzqdm ,
case when sum(self_built_houses_area_number) is null then 0 else sum(self_built_houses_area_number)  end self_built_houses_area_number,
case when sum(fire_lanes_number) is null then 0 else sum(fire_lanes_number)  end fire_lanes_number,
case when sum(fire_pool_number) is null then 0 else sum(fire_pool_number) end fire_pool_number,
case when sum(charging_facilities_number) is null then 0 else sum(charging_facilities_number) end charging_facilities_number,
case when sum(outdoor_fire_hydrant_number) is null then 0 else sum(outdoor_fire_hydrant_number) end outdoor_fire_hydrant_number,
case when sum(fire_water_crane_number) is null then 0 else sum(fire_water_crane_number) end fire_water_crane_number,
case when sum(fire_brigade_number) is null then 0 else sum(fire_brigade_number) end fire_brigade_number,
case when sum(fire_fighter_number) is null then 0 else sum(fire_fighter_number) end fire_fighter_number,
case when sum(fire_truck_number) is null then 0 else sum(fire_truck_number) end fire_truck_number,
case when sum(fire_station_number) is null then 0 else sum(fire_station_number) end fire_station_number,
case when sum(fire_station_personnel_number) is null then 0 else sum(fire_station_personnel_number) end fire_station_personnel_number,
case when sum(fire_station_truck_number) is null then 0 else sum(fire_station_truck_number) end fire_station_truck_number,
case when sum(electric_bicycle_number) is null then 0 else sum(electric_bicycle_number) end electric_bicycle_number,
case when sum(self_built_rental_house_number) is null then 0 else sum(self_built_rental_house_number) end self_built_rental_house_number
 FROM  zm_village_fire_safety zm,zm_department_xf_2023 cz,zm_department_xf_2023 jd,zm_department_xf_2023 qx
 where zm.village=cz.region_code and jd.region_code=zm.country {groupbyLever_code} {type_zx} and zm.county=qx.region_code and cz.regional_level='7'  and zm. is_delete is null GROUP BY qx.region_code,qx.region_name order by qx.region_code";
            }
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                  || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                  || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<List<object>>(false, "不符合规范，禁止执行");
            }
            var datas = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            return new RespRet<List<object>>(true, "Ok", datas);

        }



        /// <summary>
        /// 村庄设施汇总
        /// </summary>
        /// <param name="type_zx"></param>
        /// <param name="groupbyLever"></param>
        /// <param name="groupbyLever_code"></param>
        /// <returns></returns>

        [HttpGet("admin/custom-function/VillageFacilitySummaryYj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<List<object>> VillageFacilitySummaryYJ([FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] string groupbyLever_code)
        {
            if (string.IsNullOrWhiteSpace(groupbyLever))
            {
                return new RespRet<List<object>>(true, "分组等级不能为空");
            }
            if (string.IsNullOrWhiteSpace(groupbyLever_code))
            {
                return new RespRet<List<object>>(true, "行政区代码不能为空");
            }
            if (string.IsNullOrWhiteSpace(type_zx))
            {
                return new RespRet<List<object>>(true, "专项类型不能为空");
            }
            //专项条件
            if (type_zx == "0")
            {
                type_zx = " ";
            }
            else if (type_zx == "777")
            {
                type_zx = " and  cz.check777=1 ";
            }
            else if (type_zx == "108")
            {
                type_zx = " and cz.check108=1 ";
            }

            string sql = "";
            if (groupbyLever == "2")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and country='{groupbyLever_code}'";
                }
                sql = @$"SELECT zm.village,village_name villagename,
max(jd.region_name) townname ,
max(qx.region_name) xzqdmname,
max(jd.region_code) towncode,
max(cz.region_code) xzqdm ,
case when sum(self_built_houses_area_number) is null then 0 else sum(self_built_houses_area_number)  end self_built_houses_area_number,
case when sum(fire_lanes_number) is null then 0 else sum(fire_lanes_number)  end fire_lanes_number,
case when sum(fire_pool_number) is null then 0 else sum(fire_pool_number) end fire_pool_number,
case when sum(charging_facilities_number) is null then 0 else sum(charging_facilities_number) end charging_facilities_number,
case when sum(outdoor_fire_hydrant_number) is null then 0 else sum(outdoor_fire_hydrant_number) end outdoor_fire_hydrant_number,
case when sum(fire_water_crane_number) is null then 0 else sum(fire_water_crane_number) end fire_water_crane_number,
case when sum(fire_brigade_number) is null then 0 else sum(fire_brigade_number) end fire_brigade_number,
case when sum(fire_fighter_number) is null then 0 else sum(fire_fighter_number) end fire_fighter_number,
case when sum(fire_truck_number) is null then 0 else sum(fire_truck_number) end fire_truck_number,
case when sum(fire_station_number) is null then 0 else sum(fire_station_number) end fire_station_number,
case when sum(fire_station_personnel_number) is null then 0 else sum(fire_station_personnel_number) end fire_station_personnel_number,
case when sum(fire_station_truck_number) is null then 0 else sum(fire_station_truck_number) end fire_station_truck_number,
case when sum(electric_bicycle_number) is null then 0 else sum(electric_bicycle_number) end electric_bicycle_number,
case when sum(self_built_rental_house_number) is null then 0 else sum(self_built_rental_house_number) end self_built_rental_house_number
 FROM  zm_village_fire_safety_yj zm,zm_department_xf_2023 cz,zm_department_xf_2023 jd,zm_department_xf_2023 qx
 where zm.village=cz.region_code and jd.region_code=zm.country and zm.county=qx.region_code and cz.regional_level='7' {groupbyLever_code} {type_zx} and zm.is_delete is null GROUP BY zm.village,village_name  order by zm.village";
            }
            if (groupbyLever == "1")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and county='{groupbyLever_code}'";
                }
                sql = @$"SELECT 
max(jd.region_name) townname ,
max(qx.region_name) xzqdmname,
max(jd.region_code) towncode,
max(jd.region_code)xzqdm ,
case when sum(self_built_houses_area_number) is null then 0 else sum(self_built_houses_area_number)  end self_built_houses_area_number,
case when sum(fire_lanes_number) is null then 0 else sum(fire_lanes_number)  end fire_lanes_number,
case when sum(fire_pool_number) is null then 0 else sum(fire_pool_number) end fire_pool_number,
case when sum(charging_facilities_number) is null then 0 else sum(charging_facilities_number) end charging_facilities_number,
case when sum(outdoor_fire_hydrant_number) is null then 0 else sum(outdoor_fire_hydrant_number) end outdoor_fire_hydrant_number,
case when sum(fire_water_crane_number) is null then 0 else sum(fire_water_crane_number) end fire_water_crane_number,
case when sum(fire_brigade_number) is null then 0 else sum(fire_brigade_number) end fire_brigade_number,
case when sum(fire_fighter_number) is null then 0 else sum(fire_fighter_number) end fire_fighter_number,
case when sum(fire_truck_number) is null then 0 else sum(fire_truck_number) end fire_truck_number,
case when sum(fire_station_number) is null then 0 else sum(fire_station_number) end fire_station_number,
case when sum(fire_station_personnel_number) is null then 0 else sum(fire_station_personnel_number) end fire_station_personnel_number,
case when sum(fire_station_truck_number) is null then 0 else sum(fire_station_truck_number) end fire_station_truck_number,
case when sum(electric_bicycle_number) is null then 0 else sum(electric_bicycle_number) end electric_bicycle_number,
case when sum(self_built_rental_house_number) is null then 0 else sum(self_built_rental_house_number) end self_built_rental_house_number
 FROM  zm_village_fire_safety_yj zm,zm_department_xf_2023 cz,zm_department_xf_2023 jd,zm_department_xf_2023 qx
 where zm.village=cz.region_code and jd.region_code=zm.country {groupbyLever_code} and zm.county=qx.region_code and cz.regional_level='7'  {type_zx}  and zm. is_delete is null GROUP BY jd.region_code,jd,jd.region_name order by jd.region_code";
            }

            if (groupbyLever == "0")
            {
                if (groupbyLever_code == "110000")
                {
                    groupbyLever_code = " ";
                }
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and county='{groupbyLever_code}'";
                }

                sql = @$"SELECT 
max(qx.region_name) xzqdmname,
max(qx.region_code)xzqdm ,
case when sum(self_built_houses_area_number) is null then 0 else sum(self_built_houses_area_number)  end self_built_houses_area_number,
case when sum(fire_lanes_number) is null then 0 else sum(fire_lanes_number)  end fire_lanes_number,
case when sum(fire_pool_number) is null then 0 else sum(fire_pool_number) end fire_pool_number,
case when sum(charging_facilities_number) is null then 0 else sum(charging_facilities_number) end charging_facilities_number,
case when sum(outdoor_fire_hydrant_number) is null then 0 else sum(outdoor_fire_hydrant_number) end outdoor_fire_hydrant_number,
case when sum(fire_water_crane_number) is null then 0 else sum(fire_water_crane_number) end fire_water_crane_number,
case when sum(fire_brigade_number) is null then 0 else sum(fire_brigade_number) end fire_brigade_number,
case when sum(fire_fighter_number) is null then 0 else sum(fire_fighter_number) end fire_fighter_number,
case when sum(fire_truck_number) is null then 0 else sum(fire_truck_number) end fire_truck_number,
case when sum(fire_station_number) is null then 0 else sum(fire_station_number) end fire_station_number,
case when sum(fire_station_personnel_number) is null then 0 else sum(fire_station_personnel_number) end fire_station_personnel_number,
case when sum(fire_station_truck_number) is null then 0 else sum(fire_station_truck_number) end fire_station_truck_number,
case when sum(electric_bicycle_number) is null then 0 else sum(electric_bicycle_number) end electric_bicycle_number,
case when sum(self_built_rental_house_number) is null then 0 else sum(self_built_rental_house_number) end self_built_rental_house_number
 FROM  zm_village_fire_safety_yj zm,zm_department_xf_2023 cz,zm_department_xf_2023 jd,zm_department_xf_2023 qx
 where zm.village=cz.region_code and jd.region_code=zm.country {groupbyLever_code} {type_zx} and zm.county=qx.region_code and cz.regional_level='7'  and zm. is_delete is null GROUP BY qx.region_code,qx.region_name order by qx.region_code";
            }
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                  || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                  || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<List<object>>(false, "不符合规范，禁止执行");
            }
            var datas = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            return new RespRet<List<object>>(true, "Ok", datas);

        }



        /// <summary>
        /// 总项明细
        /// </summary>
        /// <param name="id"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet("admin/custom-function/GeneralDetail")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public new RespRet<Page<object>> GeneralDetail([FromQuery] string type_zx, [FromQuery] string groupbyLever, [FromQuery] string groupbyLever_code, string groupbyLever_code_project, int pageindex, int pagesize)
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<Page<object>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<Page<object>>(false, "用户名不存在");
            }
            if (type_zx == "777")
            {
                type_zx = "and v.check777 = '1'";
            }
            else if (type_zx == "108")
            {
                type_zx = "and v.check108 = '1'";
            }
            else if (type_zx == "107")
            {
                type_zx = "and v.check107 = '1'";
            }
            else
            {
                type_zx = " ";
            }
            string sql = "";
            string totalsql = "";
            string codewhere = "";
            //根据用户角色过滤
            if (curuser.RoleType > 1)
            {
                if (curuser.RoleType == 3)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and xzqdm='{RegionCode}'";
                }
                else if (curuser.RoleType == 4)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and town='{RegionCode}'";
                    if (groupbyLever == "0" || groupbyLever == "1")
                    {
                        groupbyLever = "2";
                    }
                }
                else if (curuser.RoleType == 5)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"];
                    codewhere = $"and village='{RegionCode}'";
                    groupbyLever = "2";
                }
            }

            if (string.IsNullOrEmpty(groupbyLever))
            {
                return new RespRet<Page<object>>(false, "分组等级必须传递");
            }
            if (groupbyLever == "0")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    if (groupbyLever_code == "110000")
                    {
                        groupbyLever_code = " ";
                    }
                    else
                    {
                        groupbyLever_code = $"and qx.region_code='{groupbyLever_code}' ";
                    }

                }
            }
            if (groupbyLever == "1")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and jd.region_code='{groupbyLever_code}' ";
                }
            }
            if (groupbyLever == "2")
            {
                if (!string.IsNullOrWhiteSpace(groupbyLever_code))
                {
                    groupbyLever_code = $"and v.region_code='{groupbyLever_code}' ";
                }
            }
            int total = 0;
            //存量房屋有隐
            if (groupbyLever_code_project == "fxhouse315")
            {
                sql = @$"select qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7'  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY  v.region_code limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7'  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY  v.region_code ";
            }
            //存量房屋消除
            if (groupbyLever_code_project == "cl_scfw315")
            {
                sql = @$"select qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is not null and zm.fwbh not in (select zm.fwbh
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is  null  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name  ORDER BY  v.region_code)  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY  v.region_code limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select qx.region_name xzqdmname
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is not null and zm.fwbh not in (select zm.fwbh
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is  null  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name  ORDER BY  v.region_code)  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY  v.region_code ";
            }
            //存量房屋剩余
            if (groupbyLever_code_project == "cl_syfw315")
            {
                sql = @$"select qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is  null  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name  ORDER BY  v.region_code limit {pagesize} offset {(pageindex - 1) * pagesize}";
                totalsql = @$"select v.region_code
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code {type_zx}{groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is  null  and yhfx_time<= '2023-03-15 23:59:59'  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name  ORDER BY  v.region_code ";
            }
            //存量隐患数量
            if (groupbyLever_code_project == "cl_fx315")
            {
                sql = @$"select zm.fwbh fwbh ,case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time<='2023-03-15 23:59:59' ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";

                totalsql = @$"select zm.village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time<='2023-03-15 23:59:59' ORDER BY zm.village  ";
            }
            //存量隐患消除
            if (groupbyLever_code_project == "cl_xc315")
            {

                sql = @$"select zm.fwbh fwbh , case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7' and  yhxc_time is not null  and yhfx_time<='2023-03-15 23:59:59'   ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";

                totalsql = @$"select qx.region_name 
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhxc_time is not null  and yhfx_time<='2023-03-15 23:59:59'  ORDER BY zm.village  ";
            }
            //存量隐患剩余
            if (groupbyLever_code_project == "cl_sy315")
            {
                sql = @$"select zm.fwbh fwbh , case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time<='2023-03-15 23:59:59'  and (yhxc_time is null) ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select zm.village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time<='2023-03-15 23:59:59'  and (yhxc_time is null ) ORDER BY zm.village ";
            }
            //新增隐患数
            if (groupbyLever_code_project == "xz")
            {
                sql = @$"select zm.fwbh fwbh,case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select zm.village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' ORDER BY zm.village  ";
            }

            //新增消除隐患数
            if (groupbyLever_code_project == "xc_all")
            {
                sql = @$"select zm.fwbh fwbh,case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' and yhxc_time is not null ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select zm.village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' and yhxc_time is not null ORDER BY zm.village ";
            }

            //新增剩余隐患数
            if (groupbyLever_code_project == "sy_all")
            {
                sql = @$"select zm.fwbh fwbh,case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' and yhxc_time is  null ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select zm.village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and  yhfx_time>'2023-03-15 23:59:59' and yhxc_time is  null ORDER BY zm.village";
            }

            //新增剩余隐患数
            if (groupbyLever_code_project == "sy_315")
            {
                sql = @$"select zm.fwbh fwbh,case  type  when 0 then '居住'else '商业' END as cstype,csmc as PlaceName, (select nickname from zm_user where  number=yhfx_by) as yhfx_name ,(select nickname from zm_user where  number=yhxc_by) as yhxc_name,yhfx_by,yhxc_by,place_id, yhfx_time,yhxc_time, qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,
csmc,address ,v.region_name villagename,v.region_code village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and   yhxc_time is  null ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize}  ";
                totalsql = @$"select zm.village
from zm_xf_pc_detailed zm,zm_department_xf_2023 v,zm_department_xf_2023 jd,zm_department_xf_2023 qx,zm_buildings_layer fw   where fw.fwbh=zm.fwbh 
and zm.town=jd.region_code and qx.region_code=zm.xzqdm {groupbyLever_code} and  zm.village=v.region_code {type_zx}
and v.regional_level='7'  and   yhxc_time is  null ORDER BY zm.village ";
            }

            //存量房屋消除
            if (groupbyLever_code_project == "xyyhfw")
            {
                sql = @$"select  qx.region_name xzqdmname,qx.region_code xzqdm,jd.region_name townname,jd.region_code town,zm.fwbh fwbh,address,
                        v.region_name villagename,v.region_code village
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code  {type_zx}  {groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is null  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY village limit {pagesize} offset {(pageindex - 1) * pagesize} ";
                totalsql = @$"select zm.fwbh
 from zm_xf_pc_detailed zm,zm_department_xf_2023 v, zm_department_xf_2023 jd,zm_department_xf_2023 qx, zm_buildings_layer fw where fw.fwbh = zm.fwbh and zm.town = jd.region_code and
                         qx.region_code = zm.xzqdm and zm.village = v.region_code  {type_zx}  {groupbyLever_code}
                         and v.regional_level = '7' and yhxc_time is null  GROUP by  zm.fwbh,qx.region_name,qx.region_code,jd.region_code
                        ,jd.region_name,address,v.region_code,v.region_name ORDER BY v.region_code ";
            }
            //防止注入
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
            || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
            || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
            }
            var totals = _dbContext.Database.GetDbConnection().Query<object>(totalsql).ToList();
            var datas = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            return new RespRet<Page<object>>(true, datas.Count().ToString(), new Page<object> { Items = datas, NextPageIndex = pageindex + 1, PageSize = pagesize, PageTotal = totals.Count(), Total = totals.Count() });
        }









        /// <summary>
        /// 自定义方法执行
        /// </summary>
        /// <param name="id"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet("admin/custom-function/excute")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public Object QueryBySql([FromQuery] string id, string? groupname, string param)
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<object>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<List<object>>(false, "用户名不存在");
            }

            //if (curuser.RoleType > 3)
            //{
            //    return new RespRet<List<object>>(false, "无权限");
            //}
            var curuserDto = _mapper.Map<UserDto>(curuser);

            var sql = _dbContext.Database.GetDbConnection().Query<string>($@"select value 
from zm_sql where id=@id", new { id = id }).FirstOrDefault();
            if (string.IsNullOrEmpty(sql))
            {
                return new RespRet<List<object>>(false, "未查询到自定义方法");
            }

            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
                || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
                || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<List<object>>(false, "不符合规范，禁止执行");
            }
            if (!string.IsNullOrWhiteSpace(groupname))
            {
                sql = sql.Replace("@param", groupname);
                var data = _dbContext.Database.GetDbConnection().Query<PcStatDto>(sql, new { @param = groupname }).ToList();
                if (curuser.RoleType == 3 && curuser.Group == 2)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"]; // "John"
                    var region = _departmentRepository.Query().Where(c => c.RegionCode == RegionCode).FirstOrDefault(); ;
                    if (region != null)
                    {
                        data = data.Where(c => c.qxmc == region.RegionName).ToList();
                        return new RespRet<List<PcStatDto>>(true, "Ok", data);
                    }
                }
                if (curuser.RoleType == 4 && curuser.Group == 2)
                {
                    JObject obj = JObject.Parse(curuser.District);
                    string RegionCode = (string)obj["RegionCode"]; // "John"
                    var region = _departmentRepository.Query().Where(c => c.RegionCode == RegionCode).FirstOrDefault(); ;
                    if (region != null)
                    {
                        data = data.Where(c => c.jzmc == region.RegionName).ToList();
                        return new RespRet<List<PcStatDto>>(true, "Ok", data);
                    }
                }
            }
            Logger.LogDebug($"{sql}");
            var datas = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @param = groupname }).ToList();
            return new RespRet<List<object>>(true, "Ok", datas);
        }

        /// <summary>
        /// 自定义方法执行
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("admin/custom-function/excute")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<object>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<List<object>> QueryBySql2([FromQuery] string id, [FromBody] KeyValueInput request)
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<object>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<List<object>>(false, "用户名不存在");
            }

            if (curuser.RoleType > 3)
            {
                return new RespRet<List<object>>(false, "无权限");
            }

            var curuserDto = _mapper.Map<UserDto>(curuser);

            var sql = _dbContext.Database.GetDbConnection().Query<string>($@"select value 
from zm_sql where id=@id", new { id = id }).FirstOrDefault();
            if (string.IsNullOrEmpty(sql))
            {
                return new RespRet<List<object>>(false, "未查询到自定义方法");
            }

            //if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
            //    || sql.Contains("delete ", StringComparison.OrdinalIgnoreCase)
            //    || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            //{
            //    return new RespRet<List<object>>(false, "不符合规范，禁止执行");
            //}

            if (request.KeyValues != null)
            {
                foreach (var item in request.KeyValues)
                {
                    sql = sql.Replace($"@{item.Key}", item.Value);
                }
            }

            Logger.LogDebug($"{sql}");
            var datas = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            return new RespRet<List<object>>(true, "Ok", datas);
        }

        /// <summary>
        /// 获取用户信息列表
        /// </summary>
        /// <param name="pageRequest">查询参数</param>
        /// <returns>用户信息</returns>
        [HttpGet("admin/users/list")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<UserDto>>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<Page<UserDto>> ListUsers([FromQuery] PageUserNameRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<UserDto>>(false, "PageIndex must >= 0");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<Page<UserDto>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<Page<UserDto>>(false, "用户名不存在");
            }

            var curuserDto = _mapper.Map<UserDto>(curuser);

            if (curuserDto.Role == PermissionRoleType.Admin)
            {
                var roleTypeAdmin = Convert.ToInt16(JsonConvert.SerializeObject(PermissionRoleType.Admin));
                var roleTypeUnitAdmin = Convert.ToInt16(JsonConvert.SerializeObject(PermissionRoleType.UnitAdmin));
                var roleTypeUnitInvestigator = Convert.ToInt16(JsonConvert.SerializeObject(PermissionRoleType.UnitInvestigator));

                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

//                sbSql.Append($@"SELECT *  
//FROM zm_user 
//where (is_delete is NULL or is_delete <> 1) 
//and role_type != {roleTypeUnitAdmin} 
//and role_type != {roleTypeUnitInvestigator} 
//and role_type != {roleTypeAdmin} ");

                sbSql.Append($@"SELECT *  
FROM zm_user 
where (is_delete is NULL or is_delete <> 1) 
 ");

                if (!string.IsNullOrEmpty(pageRequest.Uname))
                {
                    sbSql.Append($@" and uname like @uname");
                    sqlParams.Add(new NpgsqlParameter("uname", $"%{pageRequest.Uname}%"));
                }

                if (!string.IsNullOrEmpty(pageRequest.Nickname))
                {
                    sbSql.Append($@" and nickname like @nickname");
                    sqlParams.Add(new NpgsqlParameter("nickname", $"%{pageRequest.Nickname}%"));
                }

                if (!string.IsNullOrEmpty(pageRequest.Jurisdiction))
                {
                    sbSql.Append($@" and jurisdiction_json like @jurisdiction_json");
                    sqlParams.Add(new NpgsqlParameter("jurisdiction_json", $"%{pageRequest.Jurisdiction}%"));
                }

                var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                if (count < 1)
                {
                    var emptyDatas = new List<UserDto>();
                    var pageData1 = new Page<UserDto>(emptyDatas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                    return new RespRet<Page<UserDto>>(true, "Ok", pageData1);
                }

                sbSql.Append($@" order by id");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

                var datas = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                        .Select(_ => _mapper.Map<UserDto>(_)).ToList();

                var pageData = new Page<UserDto>(datas
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                return new RespRet<Page<UserDto>>(true, "Ok", pageData);
            }
//            else if (curuserDto.Role == PermissionRoleType.UnitAdmin)
//            {
//                var roleType = Convert.ToInt16(JsonConvert.SerializeObject(PermissionRoleType.UnitInvestigator));

//                var sbSql = new StringBuilder();
//                var sbSqlWhere = new StringBuilder();
//                var sqlParams = new List<NpgsqlParameter>();

//                sbSql.Append($@"SELECT *  
//FROM zm_user 
//where (is_delete is NULL or is_delete <> 1) 
//and role_type = {roleType} 
//and survey_unit_id = '{curuserDto.SurveyUnitId}' ");

//                if (!string.IsNullOrEmpty(pageRequest.Uname))
//                {
//                    sbSql.Append($@" and uname like @uname");
//                    sqlParams.Add(new NpgsqlParameter("uname", $"%{pageRequest.Uname}%"));
//                }

//                if (!string.IsNullOrEmpty(pageRequest.Nickname))
//                {
//                    sbSql.Append($@" and nickname like @nickname");
//                    sqlParams.Add(new NpgsqlParameter("nickname", $"%{pageRequest.Nickname}%"));
//                }

//                if (!string.IsNullOrEmpty(pageRequest.Jurisdiction))
//                {
//                    sbSql.Append($@" and jurisdiction_json like @jurisdiction_json");
//                    sqlParams.Add(new NpgsqlParameter("jurisdiction_json", $"%{pageRequest.Jurisdiction}%"));
//                }

//                var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
//                if (count < 1)
//                {
//                    var emptyDatas = new List<UserDto>();
//                    var pageData1 = new Page<UserDto>(emptyDatas
//                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
//                    return new RespRet<Page<UserDto>>(true, "Ok", pageData1);
//                }

//                sbSql.Append($@" order by id");
//                sbSql.Append($@" limit @limit offset @offset");
//                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
//                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

//                var datas = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
//                        .Select(_ => _mapper.Map<UserDto>(_)).ToList();

//                var pageData = new Page<UserDto>(datas
//                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
//                return new RespRet<Page<UserDto>>(true, "Ok", pageData);
//            }
//            else if (curuserDto.Role == PermissionRoleType.CityUnitAdmin)
//            {
//                var roleType = Convert.ToInt16(JsonConvert.SerializeObject(PermissionRoleType.CityUnitInvestigator));

//                var sbSql = new StringBuilder();
//                var sbSqlWhere = new StringBuilder();
//                var sqlParams = new List<NpgsqlParameter>();

//                sbSql.Append($@"SELECT *  
//FROM zm_user 
//where (is_delete is NULL or is_delete <> 1) 
//and role_type = {roleType} 
//and survey_unit_id = '{curuserDto.SurveyUnitId}' ");

//                if (!string.IsNullOrEmpty(pageRequest.Uname))
//                {
//                    sbSql.Append($@" and uname like @uname");
//                    sqlParams.Add(new NpgsqlParameter("uname", $"%{pageRequest.Uname}%"));
//                }

//                if (!string.IsNullOrEmpty(pageRequest.Nickname))
//                {
//                    sbSql.Append($@" and nickname like @nickname");
//                    sqlParams.Add(new NpgsqlParameter("nickname", $"%{pageRequest.Nickname}%"));
//                }

//                if (!string.IsNullOrEmpty(pageRequest.Jurisdiction))
//                {
//                    sbSql.Append($@" and jurisdiction_json like @jurisdiction_json");
//                    sqlParams.Add(new NpgsqlParameter("jurisdiction_json", $"%{pageRequest.Jurisdiction}%"));
//                }

//                var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
//                if (count < 1)
//                {
//                    var emptyDatas = new List<UserDto>();
//                    var pageData1 = new Page<UserDto>(emptyDatas
//                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
//                    return new RespRet<Page<UserDto>>(true, "Ok", pageData1);
//                }

//                sbSql.Append($@" order by id");
//                sbSql.Append($@" limit @limit offset @offset");
//                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
//                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

//                var datas = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
//                        .Select(_ => _mapper.Map<UserDto>(_)).ToList();

//                var pageData = new Page<UserDto>(datas
//                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
//                return new RespRet<Page<UserDto>>(true, "Ok", pageData);
//            }
            else
            {
                var code = Regex.Replace(curuserDto.District.RegionCode, @"[0]{3}$", "");
               // var groupFld = "\"group\"";

                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"SELECT * FROM zm_user 
WHERE district->>'RegionCode' like '{code}%' 

and (is_delete is NULL or is_delete <> 1)");

                if (curuserDto.Role == PermissionRoleType.Area)
                {
                    sbSql.Append($@" and (role_type BETWEEN {curuser.RoleType + 1} and 7)");
                }
                else if (curuserDto.Role == PermissionRoleType.City)
                {
                    sbSql.Append($@" and ((role_type BETWEEN {curuser.RoleType + 1} and 6) or role_type = 9)");
                }
                else
                {
                    sbSql.Append($@" and (role_type BETWEEN {curuser.RoleType + 1} and 6)");
                }

                if (!string.IsNullOrEmpty(pageRequest.Uname))
                {
                    sbSql.Append($@" and uname like @uname");
                    sqlParams.Add(new NpgsqlParameter("uname", $"%{pageRequest.Uname}%"));
                }

                if (!string.IsNullOrEmpty(pageRequest.Nickname))
                {
                    sbSql.Append($@" and nickname like @nickname");
                    sqlParams.Add(new NpgsqlParameter("nickname", $"%{pageRequest.Nickname}%"));
                }

                if (!string.IsNullOrEmpty(pageRequest.Jurisdiction))
                {
                    sbSql.Append($@" and jurisdiction_json like @jurisdiction_json");
                    sqlParams.Add(new NpgsqlParameter("jurisdiction_json", $"%{pageRequest.Jurisdiction}%"));
                }

                var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                if (count < 1)
                {
                    var emptyDatas = new List<UserDto>();
                    var pageData1 = new Page<UserDto>(emptyDatas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                    return new RespRet<Page<UserDto>>(true, "Ok", pageData1);
                }

                sbSql.Append($@" order by id");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

                var datas = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                    .Select(_ => _mapper.Map<UserDto>(_)).ToList();

                var pageData = new Page<UserDto>(datas
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                return new RespRet<Page<UserDto>>(true, "Ok", pageData);
            }
        }


        /// <summary>
        /// 用户信息自查
        /// </summary>
        /// <param name="pageRequest">查询参数</param>
        /// <returns>用户信息自查</returns>
        [HttpGet("admin/users/listjb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<UserDtojb>>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<Page<UserDtojb>> ListUsersjb([FromQuery] PageUserNameRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<UserDtojb>>(false, "PageIndex must >= 0");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<Page<UserDtojb>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<Page<UserDtojb>>(false, "用户名不存在");
            }



            var curuserDto = _mapper.Map<UserDto>(curuser);
            string sbSqlWhereCode ="";
            if (curuserDto.Role != PermissionRoleType.Admin)
            {
                var code = Regex.Replace(curuserDto.District.RegionCode, @"[0]{3}$", "");
                // var groupFld = "\"group\"";

                sbSqlWhereCode = $@" and  bb.villagedm  like '{code}%'";
            }

            if (!string.IsNullOrEmpty(pageRequest.disabled))
            {

                if (pageRequest.disabled == "0")
                {
                    sbSqlWhereCode = $@" and  aa.disabled  = 0";
                }
                else if (pageRequest.disabled == "1")
                {
                    sbSqlWhereCode = $@" and  aa.disabled  = 1";
                }


            }


            if (string.IsNullOrEmpty(pageRequest.Fwbh) && string.IsNullOrEmpty(pageRequest.Add) && string.IsNullOrEmpty(pageRequest.fzxm))
            {
                var pageData = new Page<UserDtojb>();
                return new RespRet<Page<UserDtojb>>(true, "Ok", pageData);
            }
            else
            {
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"SELECT  aa.id as id,aa.qaakey as qaakey, aa.number  as  fwbh, bb.xzq as xzq , bb.town as jxz,  bb.village as cz,nickname as fzxm ,bb.address,CASE WHEN disabled = 1 THEN '已解绑' ELSE '未解绑' END AS disabled  FROM zm_user AS aa INNER JOIN zm_buildings AS bb ON aa.number = bb.fwbh WHERE aa.role_type='6' and ( aa.is_delete is NULL or  aa.is_delete <> 1)");
                sbSql.Append(sbSqlWhereCode);
                if (!string.IsNullOrEmpty(pageRequest.Fwbh))
                {
                    sbSql.Append($@" and aa.fwbh in ('{pageRequest.Fwbh}') ");
                }
                if (!string.IsNullOrEmpty(pageRequest.Add))
                {
                    sbSql.Append($@" and bb.address like '{pageRequest.Add}%'");
                }
                if (!string.IsNullOrEmpty(pageRequest.fzxm))
                {
                    sbSql.Append($@" and nickname like '{pageRequest.fzxm}%'");
                }

                var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                if (count < 1)
                {
                    var emptyDatas = new List<UserDtojb>();
                    var pageData1 = new Page<UserDtojb>(emptyDatas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                    return new RespRet<Page<UserDtojb>>(true, "Ok", pageData1);
                }

                sbSql.Append($@" order by id");
                sbSql.Append($@" limit {pageRequest.Limit} offset {pageRequest.Limit * pageRequest.PageIndex}");

                var datas = _dbContext.UserDtojb.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                    .Select(_ => _mapper.Map<UserDtojb>(_)).ToList();

                var pageData = new Page<UserDtojb>(datas
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                return new RespRet<Page<UserDtojb>>(true, "Ok", pageData);
            }

        }

        /// <summary>
        /// 用户信息村级
        /// </summary>
        /// <param name="pageRequest">查询参数</param>
        /// <returns>用户信息村级</returns>
        [HttpGet("admin/users/listjbcj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<UserDtojb>>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<Page<UserDtojb>> ListUsersjbcj([FromQuery] PageUserNameRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<UserDtojb>>(false, "PageIndex must >= 0");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<Page<UserDtojb>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<Page<UserDtojb>>(false, "用户名不存在");
            }



            var curuserDto = _mapper.Map<UserDto>(curuser);
            string sbSqlWhereCode = "";
            //if (curuserDto.Role != PermissionRoleType.Admin)
            //{
            //    var code = Regex.Replace(curuserDto.District.RegionCode, @"[0]{3}$", "");
            //    // var groupFld = "\"group\"";

            //    sbSqlWhereCode = $@" and  bb.village  like '{code}%'";
            //}
            if (!string.IsNullOrEmpty(pageRequest.disabled))
            {
               
                if (pageRequest.disabled == "0")
                {
                    sbSqlWhereCode = $@" and  aa.disabled  = 0";
                }
                else if (pageRequest.disabled == "1")
                {
                    sbSqlWhereCode = $@" and  aa.disabled  = 1";
                }


            }

            try
            {

                if (string.IsNullOrEmpty(pageRequest.fzxm))
                {
                    var pageData = new Page<UserDtojb>();
                    return new RespRet<Page<UserDtojb>>(true, "Ok", pageData);
                }
                else
                {
                    var sbSql = new StringBuilder();
                    var sbSqlWhere = new StringBuilder();
                    var sqlParams = new List<NpgsqlParameter>();
                    if (pageRequest.roletype == "5")
                    {
                        sbSql.Append($@"SELECT aa.number as id,aa.qaakey as qaakey, aa.number  as  fwbh, bb.xzqdmname as xzq , bb.townname as jxz, case when role_type='2' then '市级角色' when role_type='3' then '区级角色' when role_type='4' then '乡镇角色' when role_type='5' then '村级角色' end role_type, bb.villagename as cz,nickname as fzxm ,bb.rank_name as address,CASE WHEN disabled = 1 THEN '已解绑' ELSE '未解绑' END AS disabled FROM zm_user_cj AS aa LEFT  JOIN zm_department_xf_2024 AS bb ON aa.district ->> 'RegionCode'  = bb.village    WHERE  ( aa.is_delete is NULL or  aa.is_delete <> 1)");

                    }
                    else if (pageRequest.roletype == "4") 
                    {
                        sbSql.Append($@"SELECT DISTINCT aa.number as id,aa.qaakey as qaakey, aa.number  as  fwbh, bb.xzqdmname as xzq , bb.townname as jxz, case when role_type='2' then '市级角色' when role_type='3' then '区级角色' when role_type='4' then '乡镇角色' when role_type='5' then '村级角色' end role_type, '' cz,nickname as fzxm ,bb.rank_name as address,CASE WHEN disabled = 1 THEN '已解绑' ELSE '未解绑' END AS disabled FROM zm_user_cj AS aa LEFT  JOIN zm_department_xf_2024 AS bb ON aa.district ->> 'RegionCode'  = bb.town     WHERE  ( aa.is_delete is NULL or  aa.is_delete <> 1)");

                    }
                    sbSql.Append(sbSqlWhereCode);
                    if (!string.IsNullOrEmpty(pageRequest.Fwbh))
                    {
                        sbSql.Append($@" and aa.number in ('{pageRequest.Fwbh}') ");
                    }
                    if (!string.IsNullOrEmpty(pageRequest.Add))
                    {
                        sbSql.Append($@" and bb.address like '{pageRequest.Add}%'");
                    }
                    if (!string.IsNullOrEmpty(pageRequest.fzxm))
                    {
                        sbSql.Append($@" and nickname like '{pageRequest.fzxm}%'");
                    }
                    if (!string.IsNullOrEmpty(pageRequest.roletype))
                    {
                        sbSql.Append($@" and role_type='"+ pageRequest.roletype + "'");
                    }
                    var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                    if (count < 1)
                    {
                        var emptyDatas = new List<UserDtojb>();
                        var pageData1 = new Page<UserDtojb>(emptyDatas
                        , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                        return new RespRet<Page<UserDtojb>>(true, "Ok", pageData1);
                    }

                    sbSql.Append($@" order by id");
                    sbSql.Append($@" limit {pageRequest.Limit} offset {pageRequest.Limit * pageRequest.PageIndex}");

                    var datas = _dbContext.UserDtojb.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                        .Select(_ => _mapper.Map<UserDtojb>(_)).ToList();

                    var pageData = new Page<UserDtojb>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                    return new RespRet<Page<UserDtojb>>(true, "Ok", pageData);
                }

            }
            catch (Exception ex)
            {
                return new RespRet<Page<UserDtojb>>(true, "err" + ex.ToString(), null);

            }
        }
        /// <summary>
        /// 根据角色类型获取用户信息列表
        /// </summary>
        /// <param name="pageRequest">查询参数</param>
        /// <returns>用户信息</returns>
        [HttpGet("admin/users/list/by-role")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<UserDto>>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<Page<UserDto>> ListUsers([FromQuery] PageUserRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<UserDto>>(false, "PageIndex must >= 0");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<Page<UserDto>>(false, "user not logined");
            }

            var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == curuser)
            {
                return new RespRet<Page<UserDto>>(false, "用户名不存在");
            }

            var curuserDto = _mapper.Map<UserDto>(curuser);

            Page<UserDto> users = null;
            var roleType = Convert.ToInt16(JsonConvert.SerializeObject(pageRequest.RoleType));

            if (curuserDto.Role == PermissionRoleType.Admin)
            {
                users = (from user in _dbContext.ZmUser
                         where user.IsDelete != 1
                         where user.RoleType != null
                         where user.RoleType == roleType
                         select _mapper.Map<UserDto>(user))
                         .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
            }
            else
            {
                if (curuserDto.Role == PermissionRoleType.Area
                    && pageRequest.RoleType == PermissionRoleType.UnitAdmin)// 获取区县单位管理员
                {
                    // 获取相同行政区、角色、组的管理员
                    //var groupFld = "\"group\"";
                    var sameDistrictUser = _dbContext.ZmUser.FromSqlRaw($@"SELECT * FROM zm_user 
WHERE district->>'RegionCode' = '{curuserDto.District.RegionCode}' 
and role_type = {curuser.RoleType} ")?.Select(_ => _.Number)?.ToList();
                    if (null == sameDistrictUser || sameDistrictUser.Count < 1)
                    {
                        return new RespRet<Page<UserDto>>(false, "没有管理员");
                    }

                    users = (from user in _dbContext.ZmUser
                             where user.IsDelete != 1
                             where sameDistrictUser.Contains(user.CreateBy)
                             where user.RoleType != null
                             where user.RoleType == roleType
                             // where user.SurveyUnitId == null
                             select _mapper.Map<UserDto>(user))
                             .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
                else if (curuserDto.Role == PermissionRoleType.City
                    && pageRequest.RoleType == PermissionRoleType.CityUnitAdmin)// 获取市级单位管理员
                {
                    // 获取相同行政区、角色、组的管理员
                  
                    var sameDistrictUser = _dbContext.ZmUser.FromSqlRaw($@"SELECT * FROM zm_user 
WHERE district->>'RegionCode' = '{curuserDto.District.RegionCode}' 
and role_type = {curuser.RoleType} ")?.Select(_ => _.Number)?.ToList();
                    if (null == sameDistrictUser || sameDistrictUser.Count < 1)
                    {
                        return new RespRet<Page<UserDto>>(false, "没有管理员");
                    }

                    users = (from user in _dbContext.ZmUser
                             where user.IsDelete != 1
                             where sameDistrictUser.Contains(user.CreateBy)
                             where user.RoleType != null
                             where user.RoleType == roleType
                             //where user.SurveyUnitId == null
                             select _mapper.Map<UserDto>(user))
                             .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
                else
                {
                    var code = Regex.Replace(curuserDto.District.RegionCode, @"[0]{3}$", "");
                  

                    var sbSql = new StringBuilder();
                    var sqlParams = new List<NpgsqlParameter>();
                    sbSql.Append($@"SELECT * FROM zm_user 
WHERE district->>'RegionCode' like '{code}%' 
and role_type = {roleType}
and (is_delete is NULL or is_delete <> 1)");

                    var count = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString()).Count();

                    sbSql.Append($@" order by id");
                    sbSql.Append($@" limit @limit offset @offset");
                    sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                    sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

                    var datas = _dbContext.ZmUser.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                        .Select(_ => _mapper.Map<UserDto>(_)).ToList();

                    users = new Page<UserDto>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                }
            }

            return new RespRet<Page<UserDto>>(true, "Ok", users);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userNumber"></param>
        /// <returns>用户信息</returns>
        [HttpGet("admin/users/{userNumber}/info")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<UserDto>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<UserDto> GetUserInfo([FromRoute] string userNumber)
        {
            if (!ModelState.IsValid)
            {
                return new RespRet<UserDto>(false, "Invalid Request");
            }

            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<UserDto>(false, "用户名必须输入");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<UserDto>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<UserDto>(false, "用户名不存在");
            }

            return new RespRet<UserDto>(true, "Ok", _mapper.Map<UserDto>(user));
        }

        /// <summary>
        /// 获取角色类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("admin/role-types")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<RoleTypeEnumValueDto>>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<List<RoleTypeEnumValueDto>> GetRoleTypes()
        {
            if (!ModelState.IsValid)
            {
                return new RespRet<List<RoleTypeEnumValueDto>>(false, "Invalid Request");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<RoleTypeEnumValueDto>>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<List<RoleTypeEnumValueDto>>(false, "用户名不存在");
            }

            var datas = new List<RoleTypeEnumValueDto>();
            foreach (var item in Enum.GetValues(typeof(PermissionRoleType)))
            {
                string displayName = string.Empty;
                var objs = item.GetType().GetField(item.ToString())
                    .GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs.Length > 0)
                {
                    var descriptionAttribute = objs[0] as DescriptionAttribute;
                    if (descriptionAttribute != null)
                    {
                        displayName = descriptionAttribute.Description;
                    }
                }

                var data = new RoleTypeEnumValueDto();
                data.Role = (PermissionRoleType)Enum.ToObject(typeof(PermissionRoleType), item);
                data.Name = displayName;

                //if (data.Role == PermissionRoleType.Community)
                //{
                //    continue;
                //}
                if (data.Role == PermissionRoleType.Investigator)
                {
                    continue;
                }
                var dataRoleInt = Convert.ToInt16(JsonConvert.SerializeObject(data.Role));
                if (dataRoleInt > user.RoleType)
                {
                    if (user.RoleType != 2
                        && user.RoleType != 3 && user.RoleType != 7)// 非市级、区县管理员不添加单位管理员和单位调查员
                    {
                        if (dataRoleInt >= 7)
                        {
                            continue;
                        }
                    }

                    if (user.RoleType == 2)//市级管理员
                    {
                        if (data.Role == PermissionRoleType.UnitAdmin
                            || data.Role == PermissionRoleType.UnitInvestigator)
                        {
                            continue;
                        }

                        if (data.Role == PermissionRoleType.CityUnitAdmin
                            && user.Group != 1)
                        {
                            continue;
                        }

                        if (data.Role == PermissionRoleType.CityUnitInvestigator)
                        {
                            continue;
                        }
                    }

                    if (user.RoleType == 3)//区县管理员
                    {
                        if (data.Role == PermissionRoleType.UnitAdmin
                            && user.Group != 1)
                        {
                            continue;
                        }

                        if (data.Role == PermissionRoleType.UnitInvestigator)
                        {
                            continue;
                        }

                        if (data.Role == PermissionRoleType.CityUnitAdmin
                           || data.Role == PermissionRoleType.CityUnitInvestigator)
                        {
                            continue;
                        }
                    }

                    datas.Add(data);
                }
            }

            return new RespRet<List<RoleTypeEnumValueDto>>(true, "Ok", datas);
        }

        /// <summary>
        /// 获取用户组类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("admin/group-types")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<GroupTypeEnumValueDto>>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet<List<GroupTypeEnumValueDto>> GetGroupTypes()
        {
            if (!ModelState.IsValid)
            {
                return new RespRet<List<GroupTypeEnumValueDto>>(false, "Invalid Request");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<GroupTypeEnumValueDto>>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<List<GroupTypeEnumValueDto>>(false, "用户名不存在");
            }

            var userDto = _mapper.Map<UserDto>(user);

            var datas = new List<GroupTypeEnumValueDto>();
            foreach (var item in Enum.GetValues(typeof(UserGroupType)))
            {
                string displayName = string.Empty;
                var objs = item.GetType().GetField(item.ToString())
                    .GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs.Length > 0)
                {
                    var descriptionAttribute = objs[0] as DescriptionAttribute;
                    if (descriptionAttribute != null)
                    {
                        displayName = descriptionAttribute.Description;
                    }
                }

                var type = (UserGroupType)Enum.ToObject(typeof(UserGroupType), item);
                if (type != UserGroupType.Unknown)
                {
                    if (userDto.Role == PermissionRoleType.Admin)
                    {
                        var data = new GroupTypeEnumValueDto();
                        data.Group = type;
                        data.Name = displayName;
                        datas.Add(data);
                    }
                    else
                    {
                        if (type == userDto.UserGroup)
                        {
                            var data = new GroupTypeEnumValueDto();
                            data.Group = type;
                            data.Name = displayName;
                            datas.Add(data);
                            break;
                        }
                    }
                }
            }

            return new RespRet<List<GroupTypeEnumValueDto>>(true, "Ok", datas);
        }

        /// <summary>
        /// 获取行政区树级结构
        /// </summary>
        /// <returns></returns>
        [HttpGet("admin/district-tree")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<DepartmentDto>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<List<DepartmentDto>> GetDepartmentTree()
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<List<DepartmentDto>>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<List<DepartmentDto>>(false, "用户名不存在");
            }

            var roleType = (PermissionRoleType)user.RoleType;
            if (roleType == PermissionRoleType.Admin)
            {
                var datas = (from d in _dbContext.ZmDepartment
                             select _mapper.Map<DepartmentDto>(d)).ToList();
                return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
            }
            else
            {
                if (user.Jurisdiction != null)
                {
                    var jurisdictionCodes = JsonConvert
                        .DeserializeObject<List<SimpleDepartmentDto>>(user.Jurisdiction);
                    var sbSql = new System.Text.StringBuilder();
                    var sbSqlWhere = new System.Text.StringBuilder();
                    var sqlParams = new List<Npgsql.NpgsqlParameter>();

                    for (int i = 0; i < jurisdictionCodes.Count; i++)
                    {
                        if (i > 0)
                        {
                            sbSqlWhere.Append($",@code{i}");
                            sqlParams.Add(new Npgsql.NpgsqlParameter($"code{i}", jurisdictionCodes[i].RegionCode));
                        }
                        else
                        {
                            sbSqlWhere.Append($"@code{i}");
                            sqlParams.Add(new Npgsql.NpgsqlParameter($"code{i}", jurisdictionCodes[i].RegionCode));
                        }
                    }

                    sbSql.Append(@$"WITH RECURSIVE res AS (
  SELECT * FROM zm_department WHERE region_code IN ({sbSqlWhere})
  UNION ALL
  SELECT t1.*
  FROM zm_department t1
    INNER JOIN res t2 on t1.ID = t2.parent_id
  ) SELECT
  res.*  FROM res");
                    var datas = _dbContext.ZmDepartment.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                        .Select(_ => _mapper.Map<DepartmentDto>(_)).ToList();

                    sbSql.Clear();
                    sbSql.Append(@$"WITH RECURSIVE res AS (
  SELECT * FROM zm_department WHERE region_code IN ({sbSqlWhere})
  UNION ALL
  SELECT t1.*
  FROM zm_department t1
    INNER JOIN res t2 on t1.parent_id = t2.id
  ) SELECT
  res.*  FROM res");
                    var childrenDatas = _dbContext.ZmDepartment.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray())
                        .Select(_ => _mapper.Map<DepartmentDto>(_)).ToList();
                    datas.AddRange(childrenDatas);
                    datas = datas.Distinct().ToList();
                    return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
                }
                else
                {
                    var datas = (from d in _dbContext.ZmDepartment
                                 select _mapper.Map<DepartmentDto>(d)).ToList();
                    return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
                }
            }
        }

        ///// <summary>
        ///// 按级获取行政区树级
        ///// </summary>
        ///// <param name="parentId">传null则是当前用户所在辖区</param>
        ///// <returns></returns>
        //[HttpGet("admin/district-tree/children")]
        //[Produces("application/json")]
        //[ProducesResponseType(typeof(RespRet<List<DepartmentDto>>), 200)]
        //[ProducesResponseType(403)]
        //public RespRet<List<DepartmentDto>> GetDepartmentTreeByLevel([FromQuery] string parentId)
        //{
        //    var adminUserNumber = this.CurrentUser();
        //    if (string.IsNullOrEmpty(adminUserNumber))
        //    {
        //        return new RespRet<List<DepartmentDto>>(false, "user not logined");
        //    }
        //    var user = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
        //    if (null == user)
        //    {
        //        return new RespRet<List<DepartmentDto>>(false, "用户名不存在");
        //    }

        //    var curuserDto = _mapper.Map<UserDto>(user);

        //    var roleType = (PermissionRoleType)user.RoleType;
        //    if (roleType == PermissionRoleType.Admin)
        //    {
        //        var datas = (from d in _dbContext.ZmDepartment
        //                     where d.ParentId == parentId
        //                     orderby d.RegionCode ascending
        //                     select _mapper.Map<DepartmentDto>(d)).ToList();
        //        return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
        //    }
        //    else
        //    {
        //        if (curuserDto.UserGroup == UserGroupType.Police)
        //        {
        //            if (string.IsNullOrEmpty(parentId))
        //            {
        //                var datas = (from d in _dbContext.ZmDepartment
        //                             where d.ParentId == curuserDto.District.Id
        //                             where d.Check107 != null && d.Check107 == 1
        //                             orderby d.RegionCode ascending
        //                             select _mapper.Map<DepartmentDto>(d)).ToList();
        //                return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
        //            }
        //            else
        //            {
        //                var datas = (from d in _dbContext.ZmDepartment
        //                             where d.ParentId == parentId
        //                             where d.Check107 != null && d.Check107 == 1
        //                             orderby d.RegionCode ascending
        //                             select _mapper.Map<DepartmentDto>(d)).ToList();
        //                return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
        //            }
        //        }
        //        else
        //        {
        //            if (string.IsNullOrEmpty(parentId))
        //            {
        //                var datas = (from d in _dbContext.ZmDepartment
        //                             where d.ParentId == curuserDto.District.Id
        //                             orderby d.RegionCode ascending
        //                             select _mapper.Map<DepartmentDto>(d)).ToList();
        //                return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
        //            }
        //            else
        //            {
        //                var datas = (from d in _dbContext.ZmDepartment
        //                             where d.ParentId == parentId
        //                             orderby d.RegionCode ascending
        //                             select _mapper.Map<DepartmentDto>(d)).ToList();
        //                return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
        //            }
        //        }
        //    }
        //}


        /// <summary>
        /// 按级获取行政区树级
        /// </summary>
        /// <param name="parentId">传null则是当前用户所在辖区</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("admin/district-tree/childrenlist")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<DepartmentDto>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<List<ZmBuildingLedgerDto>> GetDepartmentTree([FromQuery] string parentId)
        {
            if (string.IsNullOrWhiteSpace(parentId))
            {
                parentId = "110000";
            }
            parentId = parentId.Replace("000", "");


            //var userNumber = this.CurrentUser();
            //if (string.IsNullOrEmpty(userNumber))
            //{
            //    return new RespRet<List<ZmBuildingLedgerDto>>(false, "user not logined");
            //}

            //var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            //if (null == user)
            //{
            //    return new RespRet<List<ZmBuildingLedgerDto>>(false, "用户名不存在");
            //}

            string sql = " select xzqdm id,xzqdm regioncode,max(xzq) regionname,'110000' parentid from zm_building_ledger where xzqdm like @code  group by xzqdm order by xzqdm  ";

            int len = parentId.Length;

            if (len == 6)
            {
                sql = "select towndm id,towndm regioncode,max(town) regionname,max(xzqdm) parentid from zm_building_ledger where towndm like @code  group by towndm order by towndm  ";
            }

            if (len == 9)
            {
                sql = "select villagedm id,villagedm regioncode,max(village) regionname,max(towndm) parentid from zm_building_ledger where villagedm like @code  group by villagedm  order by villagedm ";
            }

            if (len == 12)
            {
                sql = "select villagedm id,villagedm regioncode,max(village) regionname,max(towndm) parentid from zm_building_ledger where villagedm like @code group by villagedm order by villagedm  ";
            }

            var datas = _dbContext.Database.GetDbConnection().Query<ZmBuildingLedgerDto>(sql, new {code="%"+parentId+"%" }).ToList();
            return new RespRet<List<ZmBuildingLedgerDto>>(true, "Ok", datas);
        }


        public class Region
        {
            public string ParentId { get; set; }

            public string Id { get; set; }

            public string name { get; set; }

            public string value { get; set; }

        }
        public class RegionDto
        {
            public string value { get; set; }
            public string label { get; set; }
            public List<RegionDto> children { get; set; }
        }

        [AllowAnonymous]
        [HttpGet("admin/district-tree/GetRegionTree")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<DepartmentDto>>), 200)]
        [ProducesResponseType(403)]
        public object GetRegion()
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<object>>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<Page<object>>(false, "用户名不存在");
            }
            string district = user.District;
            var options = new JsonSerializerOptions();
            options.PropertyNameCaseInsensitive = true; // 设置属性不区分大小写
            Xzq model = System.Text.Json.JsonSerializer.Deserialize<Xzq>(district, options);


            string strWhere = " where 1=1 ";
            if (user.RoleType == 3) //区级
            {
                strWhere += " and value like '" + model.RegionCode + "%'";
            }


            string sql = " select *From ( select  xzqdm id,xzqdm value,xzq name,null parentid  from zm_building_ledger  GROUP BY xzqdm,xzq \r\nunion all \r\nselect  towndm id,towndm value,town name,max(xzqdm) parentid  from zm_building_ledger  GROUP BY towndm,town \r\nunion all\r\nselect  villagedm id,villagedm value,village name,max(towndm) parentid  from zm_building_ledger  GROUP BY villagedm,village ) a  "+ strWhere+"    ORDER BY id ";
            var regiondata =_dbContext.Database.GetDbConnection().Query<Region>(sql,null).ToList();
            List<RegionDto> data = new List<RegionDto>();
            foreach (var item in regiondata)
            {
                if (item.ParentId == null)
                {
                    RegionDto addRegion = new RegionDto { value = item.value, label = item.name };
                    data.Add(addRegion);
                    PrintRegions(regiondata, addRegion, item.Id);
                }
            }
              return new RespRet<List<RegionDto>>(true, "Ok", data);
        }
        // 递归打印区域数据
        private void PrintRegions(List<Region> sys_department, RegionDto region,string id)
        {
            var regiondata = sys_department.Where(c => c.ParentId == id).ToList();
            if (regiondata != null && regiondata.Count() > 0)
            {
                region.children = new List<RegionDto>();
                foreach (var item in regiondata)
                {
                    RegionDto addRegion = new RegionDto { value = item.value, label = item.name };
                    region.children.Add(addRegion);
                    PrintRegions(sys_department, addRegion, item.Id);
                }
            }
        }












        /// <summary>
        /// 按级获取行政区树级
        /// </summary>
        /// <param name="parentId">传null则是当前用户所在辖区</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("admin/district-tree/children")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<DepartmentDto>>), 200)]
        [ProducesResponseType(403)]
        public RespRet<List<ZmBuildingLedgerDto>> GetDepartmentTreeByLevel([FromQuery] string parentId)
        {
            if (string.IsNullOrWhiteSpace(parentId))
            {
                parentId = "110000";
            }
            parentId = parentId.Replace("000", "");
          

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<List<ZmBuildingLedgerDto>>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<List<ZmBuildingLedgerDto>>(false, "用户名不存在");
            }

            var sbSql = new StringBuilder();
            var sbSqlWhere = new StringBuilder();
            var sqlParams = new List<NpgsqlParameter>();

            var sbSqlBuildingEx = new StringBuilder();

            string district = user.District;

            var options = new JsonSerializerOptions();
            options.PropertyNameCaseInsensitive = true; // 设置属性不区分大小写
            Xzq xzq = System.Text.Json.JsonSerializer.Deserialize<Xzq>(district, options);

            string sql = "";
            if (user.RoleType == 1 || user.RoleType == 2)
            {
                sql = "select xzqdm as id,xzqdm as regioncode,max(xzq)as  regionname,'110000' parentid from zm_building_ledger group by xzqdm order by xzqdm   ";
            }
            else if (user.RoleType == 3)  //区级
            {

                sql = "select towndm id,towndm regioncode,max(town) regionname,max(xzqdm) parentid from zm_building_ledger where xzqdm='"+ xzq.RegionCode+"' group by towndm order by towndm  ";

            }
            else if (user.RoleType == 4)
            {
                string towndm = xzq.RegionCode;
                if (xzq.RegionCode.Length != 12) 
                {
                    towndm = xzq.RegionCode+"000";
                }
                sql = "select villagedm id,villagedm regioncode,max(village) regionname,max(towndm) parentid from zm_building_ledger where towndm='"+ towndm + "' group by villagedm  order by villagedm ";
            }
            else if (user.RoleType == 5)
            {
                sql = "select villagedm id,villagedm regioncode,max(village) regionname,max(towndm) parentid from zm_building_ledger where villagedm='"+ xzq.RegionCode+"' group by villagedm order by villagedm  ";
            }



            int len = parentId.Length;

            if (len == 6)
            {
                sql = "select towndm id,towndm regioncode,max(town) regionname,max(xzqdm) parentid from zm_building_ledger where xzqdm='"+parentId+"' group by towndm order by towndm  ";
            }

            if (len == 9)
            {
                sql = "select villagedm id,villagedm regioncode,max(village) regionname,max(towndm) parentid from zm_building_ledger where towndm='"+parentId+"' group by villagedm  order by villagedm ";
            }

            if (len == 12)
            {
                sql = "select villagedm id,villagedm regioncode,max(village) regionname,max(towndm) parentid from zm_building_ledger where villagedm='"+parentId+"' group by villagedm order by villagedm  ";
            }

            var datas = _dbContext.Database.GetDbConnection().Query<ZmBuildingLedgerDto>(sql).ToList();
            return new RespRet<List<ZmBuildingLedgerDto>>(true, "Ok", datas);
            //}
            //else
            //{
            //    if (curuserDto.UserGroup == UserGroupType.Police)
            //    {
            //        if (string.IsNullOrEmpty(parentId))
            //        {
            //            var datas = (from d in _dbContext.ZmDepartment
            //                         where d.ParentId == curuserDto.District.Id
            //                         where d.Check107 != null && d.Check107 == 1
            //                         orderby d.RegionCode ascending
            //                         select _mapper.Map<DepartmentDto>(d)).ToList();
            //            return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
            //        }
            //        else
            //        {
            //            var datas = (from d in _dbContext.ZmDepartment
            //                         where d.ParentId == parentId
            //                         where d.Check107 != null && d.Check107 == 1
            //                         orderby d.RegionCode ascending
            //                         select _mapper.Map<DepartmentDto>(d)).ToList();
            //            return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
            //        }
            //    }
            //    else
            //    {
            //        if (string.IsNullOrEmpty(parentId))
            //        {
            //            var datas = (from d in _dbContext.ZmDepartment
            //                         where d.ParentId == curuserDto.District.Id
            //                         orderby d.RegionCode ascending
            //                         select _mapper.Map<DepartmentDto>(d)).ToList();
            //            return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
            //        }
            //        else
            //        {
            //            var datas = (from d in _dbContext.ZmDepartment
            //                         where d.ParentId == parentId
            //                         orderby d.RegionCode ascending
            //                         select _mapper.Map<DepartmentDto>(d)).ToList();
            //            return new RespRet<List<DepartmentDto>>(true, "Ok", datas);
            //        }
            //    }
            //}
        }


        /// <summary>
        /// 获取行政区信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("admin/district-tree/{code}/info")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<DepartmentDto>), 200)]
        [ProducesResponseType(403)]
        public RespRet<DepartmentDto> GetDepartmentByCode([FromRoute] string code)
        {
            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<DepartmentDto>(false, "user not logined");
            }

            var data = _departmentRepository.FirstOrDefault(_ => _.RegionCode == code);
            return new RespRet<DepartmentDto>(true, "Ok", _mapper.Map<DepartmentDto>(data));
        }

        /// <summary>
        /// 判断用户名是否已存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpGet("admin/users/exists")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<bool>), 200)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet Exists([FromQuery] string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return new RespRet<bool>(false, "Invalid param");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<bool>(false, "user not logined");
            }

            var count = _userRepository.Count(u => string.Equals(u.Uname, userName) && u.IsDelete != 1);
            if (count > 0)
            {
                return new RespRet<bool>(true, "Ok", true);
            }

            return new RespRet<bool>(true, "Ok", false);
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns>创建用户是否成功，并返回唯一编号</returns>
        [HttpPost("admin/users/create")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<string>), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet CreateUser([FromBody] CreateUserInput request)
        {
            if (!ModelState.IsValid)
            {
                return new RespRet<string>(false, "Invalid Request");
            }

            if (string.IsNullOrEmpty(request.UserName))
            {
                return new RespRet<string>(false, "用户名必须输入");
            }

            if (string.IsNullOrEmpty(request.Pwd))
            {
                return new RespRet<string>(false, "密码必须输入");
            }

            var count = _userRepository.Count(u => u.Uname == request.UserName && u.IsDelete != 1);
            if (count > 0)
            {
                return new RespRet<string>(false, "用户名已存在");
            }

            var encphone = string.Empty;
            var p = string.Empty;
            if (!string.IsNullOrEmpty(request.Phone))
            {
                // phone 限制
                if (!string.IsNullOrEmpty(request.Phone) && !UtilExtenions.IsMobilePhone(request.Phone))
                {
                    return new RespRet<string>(false, "手机号码格式不正确");
                }

                encphone = AesHelper.Encrypt(request.Phone);
                p = $"{request.Phone.Substring(0, 3)}****{request.Phone.Substring(7, 4)}";
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<string>(false, "user not logined");
            }

            if (string.IsNullOrEmpty(request.SurveyUnitId))
            {
                var curuser = _userRepository.FirstOrDefault(u => u.Number == adminUserNumber && u.IsDelete != 1);
                if (null == curuser)
                {
                    return new RespRet<Page<UserDto>>(false, "用户名不存在");
                }

                request.SurveyUnitId = curuser.SurveyUnitId;
            }

            var ipAddress = this.IpAddress();
            var userNumber = new IdWorker(1, 1).NextId().ToString();

            var randomBytes = new byte[64];
            using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                rngCryptoServiceProvider.GetBytes(randomBytes);
            }

          //  var salt = UrlBase64.Encode(randomBytes, PaddingPolicy.Discard);
            var pwd = (request.Pwd);
            var uid = SequentialGuid.SequentialGuidGenerator.Instance.NewGuid().ToString("N");


            var user = new ZmUser
            {
                Id = uid,
                Number = userNumber,
                Uname = request.UserName,
                Pwd = pwd,
                Encphone = encphone,
                Phone = p,
                Nickname = request.Nickname,
                IdCard = request.IdCard,
                Salt = "",
                SysAdmin = (short)(request.Role != PermissionRoleType.Investigator
                || request.Role != PermissionRoleType.UnitInvestigator ? 1 : 0),
                CreateBy = adminUserNumber,
                CreateOn = DateTime.Now,
                CreateIp = ipAddress,
                ModifiedBy = adminUserNumber,
                ModifiedOn = DateTime.Now,
                ModifiedIp = ipAddress,
                RoleType = Convert.ToInt16(JsonConvert.SerializeObject(request.Role)),
                Group = Convert.ToInt16(JsonConvert.SerializeObject(request.UserGroup)),
                District = JsonConvert.SerializeObject(request.DistrictCode),
                Jurisdiction = JsonConvert.SerializeObject(request.JurisdictionCodes),
                DistrictJson = request.DistrictJson,
                JurisdictionJson = request.JurisdictionJson,
                SurveyUnitId = request.SurveyUnitId
            };

            _userRepository.Insert(user);
            _userRepository.SaveChanges();

            return new RespRet<string>(true, "Ok", userNumber);
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="userNumber"></param>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        [HttpPost("admin/users/{userNumber}/edit")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet EditUser([FromRoute] string userNumber, [FromBody] EditUserInput request)
        {
            if (!ModelState.IsValid)
            {
                return new RespRet(false, "Invalid Request");
            }

            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<string>(false, "用户名必须输入");
            }

            var encphone = string.Empty;
            var p = string.Empty;
            if (!string.IsNullOrEmpty(request.Phone))
            {
                // phone 限制
                if (!string.IsNullOrEmpty(request.Phone) && !UtilExtenions.IsMobilePhone(request.Phone))
                {
                    return new RespRet<string>(false, "手机号码格式不正确");
                }

                encphone = AesHelper.Encrypt(request.Phone);
                p = $"{request.Phone.Substring(0, 3)}****{request.Phone.Substring(7, 4)}";
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet<string>(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<string>(false, "用户名不存在");
            }

            var ipAddress = this.IpAddress();

            if (!string.IsNullOrEmpty(request.Nickname))
            {
                user.Nickname = request.Nickname;
            }

            if (!string.IsNullOrEmpty(request.Phone))
            {
                user.Phone = p;
                user.Encphone = encphone;
            }

            if (!string.IsNullOrEmpty(request.IdCard))
            {
                user.IdCard = request.IdCard;
            }

            if (request.Role != PermissionRoleType.Unknown)
            {
                user.SysAdmin = (short)(request.Role != PermissionRoleType.Investigator
                    || request.Role != PermissionRoleType.UnitInvestigator ? 1 : 0);
                user.RoleType = Convert.ToInt16(JsonConvert.SerializeObject(request.Role));
            }

            if (request.UserGroup != UserGroupType.Unknown)
            {
                user.Group = Convert.ToInt16(JsonConvert.SerializeObject(request.UserGroup));
            }

            if (request.DistrictCode != null)
            {
                user.District = JsonConvert.SerializeObject(request.DistrictCode);
            }

            if (request.JurisdictionCodes != null && request.JurisdictionCodes.Count > 0)
            {
                user.Jurisdiction = JsonConvert.SerializeObject(request.JurisdictionCodes);
            }

            if (!string.IsNullOrEmpty(request.DistrictJson))
            {
                user.DistrictJson = request.DistrictJson;
            }

            if (!string.IsNullOrEmpty(request.JurisdictionJson))
            {
                user.JurisdictionJson = request.JurisdictionJson;
            }

            if (!string.IsNullOrEmpty(request.SurveyUnitId))
            {
                user.SurveyUnitId = request.SurveyUnitId;
            }

            user.ModifiedOn = DateTime.Now;
            user.ModifiedIp = ipAddress;

            _userRepository.Update(user);
            _userRepository.SaveChanges();

            return new RespRet<string>(true, "Ok", userNumber);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userNumber">用户唯一编号</param>
        /// <returns></returns>
        [HttpPost("admin/users/{userNumber}/delete")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet DeleteUser([FromRoute] string userNumber)
        {
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "userNumber not allow empty");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet(false, "user not logined");
            }

            if (string.Equals(adminUserNumber, userNumber))
            {
                return new RespRet(false, "you can not delete yourself");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber);
            if (null == user)
            {
                return new RespRet(false, "用户不存在");
            }

            var roleType = (PermissionRoleType)user.RoleType;
            if (roleType == PermissionRoleType.Admin)
            {
                return new RespRet(false, "超级管理员不允许删除");
            }

            _userRepository.Delete(user);
            _userRepository.SaveChanges();
            return new RespRet(true, "Ok");
        }


 
        /// <summary>
        /// 自查解绑(房屋编号)
        /// </summary>
        /// <param name="fwbh">用户唯一编号</param>
        /// <returns></returns>
        [HttpPost("admin/users/{fwbh}/fwbhjb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet fwbhjb([FromRoute] string fwbh)
        {
            if (string.IsNullOrEmpty(fwbh))
            {
                return new RespRet(false, "fwbh not allow empty");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet(false, "user not logined");
            }
            string sqlstr = "";
            string sqlstrwhere = "";
            sqlstrwhere = " where fwbh='" + fwbh+"'";
            string  sqlstrwherenumber = " where id='" + fwbh + "'";

            //sqlstr =
            // @"INSERT INTO zm_pc_base_jblog SELECT * FROM zm_pc_base  " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_baselog_jblog SELECT * from zm_pc_baselog  " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_yh_jblog SELECT * from zm_pc_yh   " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_yhlog_jblog SELECT * from zm_pc_yhlog " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_yhlog_dx_jblog SELECT * from zm_pc_yhlog_dx " + sqlstrwhere + @";
            //    INSERT INTO zm_user_jblog SELECT * from zm_user " + sqlstrwherenumber + @";
            //    INSERT INTO zm_pc_yhlog_dxzgson_jblog SELECT * from zm_pc_yhlog_dxzgson " + sqlstrwhere + @";";

            //sqlstr +=
            //  @"delete from zm_pc_base  " + sqlstrwhere + @";
            //    delete from zm_pc_baselog  " + sqlstrwhere + @";
            //    delete from zm_pc_yh   " + sqlstrwhere + @";
            //    delete from zm_pc_yhlog " + sqlstrwhere + @";
            //    delete from zm_pc_yhlog_dxzgson " + sqlstrwhere + @";
            //    delete from zm_user " + sqlstrwherenumber + @";
            //    delete from zm_pc_yhlog_dx " + sqlstrwhere + @";";

           sqlstr = @"update zm_user set disabled =1  " + sqlstrwherenumber ;

            var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();





            return new RespRet(true, "Ok");
        }



        /// <summary>
        /// 村级解绑(用户ID)
        /// </summary>
        /// <param name="fwbh">用户唯一编号</param>
        /// <returns></returns>
        [HttpPost("admin/users/{fwbh}/fwbhjbcj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet fwbhjbcj([FromRoute] string fwbh)
        {
            if (string.IsNullOrEmpty(fwbh))
            {
                return new RespRet(false, "fwbh not allow empty");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet(false, "user not logined");
            }
            string sqlstr = "";
            string sqlstrwhere = "";
            sqlstrwhere = " where create_by='" + fwbh + "'";
            string sqlstrwheredx = " where check_by='" + fwbh + "'";
            string sqlstrwherenumber = " where number='" + fwbh + "'";


            //sqlstr =
            // @" INSERT INTO zm_pc_base_cjjblog SELECT * FROM zm_pc_base_cj  " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_baselog_cjjblog SELECT * from zm_pc_baselog_cj  " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_yh_cjjblog SELECT * from zm_pc_yh_cj   " + sqlstrwhere + @";
            //    INSERT INTO zm_pc_yhlog_cjjblog SELECT * from zm_pc_yhlog_cj " + sqlstrwhere + @";
            //    INSERT INTO zm_user_cjjblog SELECT * from zm_user_cj " + sqlstrwherenumber + @";
            //    INSERT INTO zm_pc_yhlog_dxzgson_cjjblog SELECT * from zm_pc_yhlog_dxzgson_cj where yhlog_dx_id in (SELECT id from zm_pc_yhlog_dx_cj " + sqlstrwheredx + @");" +
            //    "INSERT INTO zm_pc_yhlog_dx_cjjblog SELECT * from zm_pc_yhlog_dx_cj " + sqlstrwheredx + @";";

            //sqlstr +=
            //  @"delete from zm_pc_base_cj  " + sqlstrwhere + @";
            //    delete from zm_pc_baselog_cj  " + sqlstrwhere + @";
            //    delete from zm_pc_yh_cj   " + sqlstrwhere + @";
            //    delete from zm_pc_yhlog_cj " + sqlstrwhere + @";
            //    delete from zm_user_cj" + sqlstrwherenumber + @";
            //    delete  from zm_pc_yhlog_dxzgson_cj where yhlog_dx_id in (SELECT id from zm_pc_yhlog_dx_cj " + sqlstrwheredx + @");" +
            //   "delete from zm_pc_yhlog_dx_cj " + sqlstrwheredx + @";";


             sqlstr = @"update zm_user_cj set disabled =1  " + sqlstrwherenumber;

            var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();

      



            return new RespRet(true, "Ok");
        }




        /// <summary>
        /// 村级解绑(用户ID)
        /// </summary>
        /// <param name="fwbh">用户唯一编号</param>
        /// <returns></returns>
        [HttpGet("admin/users/{fwbh}/updateregion")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet updateregion([FromQuery] string id, [FromQuery] string xzqdm, [FromQuery] string towndm, [FromQuery] string villagedm, [FromQuery] string role_type_name)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new RespRet(false, "number not allow empty");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet(false, "user not logined");
            }

            string regionJson = "";
            if (!string.IsNullOrEmpty(xzqdm) && !string.IsNullOrEmpty(towndm) && !string.IsNullOrEmpty(villagedm))
            {
                string sql = " select * from zm_building_ledger where villagedm='" + villagedm + "'";

                var item = _dbContext.Database.GetDbConnection().Query<object>(sql).FirstOrDefault();
                string name = "";
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (item != null)
                {
                    var properties = item as IDictionary<string, object>;
                    foreach (var model in properties)
                    {
                        if (model.Key == "village")
                        {
                            name = model.Value + "";
                        }
                    }
                }
                regionJson = "{\"Id\":\"" + villagedm + "\",\"RegionCode\":\"" + villagedm + "\",\"RegionName\":\"" + name + "\"}";
            }
            else if (!string.IsNullOrEmpty(xzqdm) && !string.IsNullOrEmpty(towndm) && string.IsNullOrEmpty(villagedm))
            {
                string sql = " select * from zm_building_ledger where towndm='" + towndm + "'";

                var item = _dbContext.Database.GetDbConnection().Query<object>(sql).FirstOrDefault();
                string name = "";
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (item != null)
                {
                    var properties = item as IDictionary<string, object>;
                    foreach (var model in properties)
                    {
                        if (model.Key == "town")
                        {
                            name = model.Value + "";
                        }
                    }
                }
                regionJson = "{\"Id\":\"" + towndm + "\",\"RegionCode\":\"" + towndm + "\",\"RegionName\":\"" + name + "\"}";
            }else if (!string.IsNullOrEmpty(xzqdm) && string.IsNullOrEmpty(towndm) && string.IsNullOrEmpty(villagedm))
            {
                string sql = " select * from zm_building_ledger where xzqdm='" + xzqdm + "'";

                var item = _dbContext.Database.GetDbConnection().Query<object>(sql).FirstOrDefault();
                string name = "";
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (item != null)
                {
                    var properties = item as IDictionary<string, object>;
                    foreach (var model in properties)
                    {
                        if (model.Key == "town")
                        {
                            name = model.Value + "";
                        }
                    }
                }
                regionJson = "{\"Id\":\"" + xzqdm + "\",\"RegionCode\":\"" + xzqdm + "\",\"RegionName\":\"" + name + "\"}";
            }
            else 
            {
                regionJson = "{\"Id\":\"110000\",\"RegionCode\":\"110000\",\"RegionName\":\"北京市\"}";
            }

            string sqlstr = @"update zm_user_cj set role_type =" + role_type_name + " ,district='" + regionJson + "' where qaakey='" + id + "'";

            var datas = _dbContext.Database.GetDbConnection().Query<object>(sqlstr).ToList();

            return new RespRet(true, "Ok");
        }


        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="userNumber">用户唯一编号</param>
        /// <param name="pwd">新密码</param>
        /// <returns></returns>
        [HttpPost("admin/users/{userNumber}/pwd-reset")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet ResetPwd([FromRoute] string userNumber, [FromQuery] string pwd)
        {
            if (string.IsNullOrEmpty(userNumber) || string.IsNullOrEmpty(pwd))
            {
                return new RespRet(false, "userNumber and pwd not allow empty");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber);
            if (null == user)
            {
                return new RespRet(false, "用户不存在");
            }

            //var pwdMd5 = (pwd + user.Salt).Md5();
            user.Pwd = pwd;
            _userRepository.Update(user);
            _userRepository.SaveChanges();
            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("admin/users/{userNumber}/disable")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet DisableUser([FromRoute] string userNumber)
        {
            return XAbleUser(userNumber, false);
        }

        /// <summary>
        /// 启用用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("admin/users/{userNumber}/enable")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        [ProducesResponseType(403)]
        [Authorize(policy: Policys.AdminOnly)]
        public RespRet EnableUser([FromRoute] string userNumber)
        {
            return XAbleUser(userNumber, true);
        }

        private RespRet XAbleUser(string userNumber, bool enable)
        {
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "userNumber not allow empty");
            }

            var adminUserNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(adminUserNumber))
            {
                return new RespRet(false, "user not logined");
            }

            if (string.Equals(adminUserNumber, userNumber))
            {
                return new RespRet(false, "you can not enable/disable yourself");
            }

            var firstOrDefault = _userRepository
                .FirstOrDefault(u => u.Number == userNumber);
            if (null != firstOrDefault)
            {
                firstOrDefault.ModifiedIp = this.IpAddress();
                firstOrDefault.Disabled = (short)(enable ? 0 : 1);
                _userRepository.Update(firstOrDefault);
                _userRepository.SaveChanges();

                return new RespRet(true, "Ok");
            }

            return new RespRet(false, "user not found");
        }
    }
}
